Handling different returns from JSON

1

I'm working on an API integration with JSON. I have not implemented anything yet in my C # code, I am currently studying the API but I have already had a question.

I have a login method that if successful returns me a type of response, and if it fails I get a totally different type.

Example:

If successful, the return is:

{
   "Autenticacao": {
          "tokenAutenticacao": "9f6530dad90c7f8eda5670"
          "idUsuario": "c7f8eda5670"
    }
}

Using json2charp I create the following class:

public class Autenticacao
{
    public string tokenAutenticacao { get; set; }
    public string idUsuario { get; set; }
}

public class LoginSucesso
{
    public Autenticacao Autenticacao { get; set; }
}

And if login fails, the return is:

{
  "status": {
    "code": 403,
    "name": "Forbidden"
  },
"mensagem": "Login falhou",
"exception": "Blah Blah blah",
"dataHora": "18/06/2015 10:47:47"
}

Converting to a C # class I have:

public class Status
{
    public int code { get; set; }
    public string name { get; set; }
}

public class LoginFalha
{
    public Status status { get; set; }
    public string mensagem { get; set; }
    public string exception { get; set; }
    public string dataHora { get; set; }
}

Note: I've changed RootObject for LoginSuccess and LoginFail.

I want to use Json.NET to deserialize the JSON object, doing something like this:

LoginSucesso resultadoJson = JsonConvert.DeserializeObject<LoginSucesso>(meuJson);

But what if login fails?

How should I handle C # code?

I treat an exception and try LoginFalha resultadoJson = JsonConvert.DeserializeObject<LoginFalha>(meuJson); ????

    
asked by anonymous 18.06.2015 / 16:42

2 answers

1

You can handle the exception, but it will be more elegant to use the JsonSchema class to validate.

Begin by declaring a string with Schema

string schemaJson = @"{
   'description': 'Autenticaçao',
   'type': 'object',
   'properties':
   {
     'tokenAutenticacao': {'type':'string'},
     'idUsuario': {'type':'string'}
  }
}";

Create a JsonSchema object by passing the schema to the constructor:

JsonSchema schema = JsonSchema.Parse(schemaJson);

Create a JObject from your json

JObject autenticacao = JObject.Parse(resultadoJson);

Validate:

bool valido = autenticacao.IsValid(schema);
    
18.06.2015 / 17:16
1

You can first convert to JObject and then check if you have a key exception before converting

var obj = JObject.parse(meuJson);

if(obj["exception"] != null)
{
    var falha = obj.ToObject<LoginFalha>();
}
else
{
    var sucesso = obj.ToObject<LoginSucesso>();
}

But you should validate with a JSchema, as indicated by @ramaral - it is a more robust solution.

    
18.06.2015 / 17:21