Handling of returns other than JSON

Asked

Viewed 548 times

1

I’m working on an API integration with JSON. I have not implemented anything yet in my code C#, I am for now studying the API but I have already come up with a question.

I have a Login method that if it succeeds returns me a type of answer, and if it fails returns me a totally different type.

Example:

If successful the return is :

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

Using json2charp 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 the 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 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 exchanged Rootobject for Loginsucesso and Loginfalha.

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

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

But what if the login fails?

How should I treat code C#?

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

2 answers

1

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

Start by declaring a string with the Schema

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

Create an object Jsonschema passing the schema to the builder:

JsonSchema schema = JsonSchema.Parse(schemaJson);

Create a Jobject from their json

JObject autenticacao = JObject.Parse(resultadoJson);

Validate:

bool valido = autenticacao.IsValid(schema);

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’s a more robust solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.