简体   繁体   中英

Any better way to solve the error handling in windows phone using json.net?

I work on a Windows phone 7.1 project target on wp7 and wp8.

I successfully fetch data from a REST api using C#. The API response me with 1 json, but it can be 2 structures.One for the correct result and one for the error message. Each of them have completely different structure.

and the HTTP status is all the same ---> 200

I translate them into 2 C# classes for the further deserializing.

What I want is to handle them differently, but you know, the deserializing needs a target C# class for the json. But How can I know which type of json does the API response me? I can figure it by my eye but how can the C# codes figure out.

What I thought is handle it with a try catch.

try
{
  //Deserializing the correct result
}
catch ( Exception ex)
{
  //Deserializing the ERROR result
}

Is there any better way for solving this?

As Alaa Masoud mentioned in the comments, if your REST API method returns a different status code for success than error (usually 200 for success or 4xx for error), you can look at that before deserializing to decide which class to use. This would be the best way to do it.

If your method returns the same status code in each case, there are a couple of other ideas you could try:

  1. You could use Linq to Json instead of deserializing into a fixed class. In other words, use JObject.Parse() , then walk the JSON looking for the properties you're interested in.
  2. You could define your fixed class to have properties of both the error and success JSON structure, then set the NullValueHandling option on the deserializer to Ignore . This will allow the deserializer to fill in the properties for which it finds values int the JSON without throwing errors. Then you can simply check the object for the success or error values. Obviously, this solution isn't as "clean" but it could work in a pinch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM