简体   繁体   中英

c# : Deserialize json Object

I am calling an api , On success I am getting json data in List format

[

    {

        "fileName": [
            "file1"
        ],
        "date": [
            "8/25/2015 0:00"
        ],
        "time": [
            "7/16/2009 16:51"
        ],
        "id": "1",
        "version_": 1},
    {

        "fileName": [
            "file1"
        ],
        "date": [
            "8/25/2015 0:00"
        ],
        "time": [
            "7/16/2009 16:51"
        ],
        "id": "1",
        "version_": 1
    }
    ]

On error,When I am passing wrong data,response is in pure json format

{
   "resultType": "error",
   "errorType": "validationError",
   "errorCode": "validation.error",
   "apiMessage": "Data Validation issue, please correct the data and try again",
   "validationErrors":    [
            {
         "errorCode": "100211",
         "path": "firstName",
         "apiMessage": "Minimum field length not reached"
      },
            {
         "errorCode": "100241",
         "path": "firstName",
         "apiMessage": "Names must have at least one alphabetic character"
      }
   ],
   "requestId": "3f6fb4b5-42a9-44e5-9ed3-6a50c6fdcc52"
}

When no data is present I am getting

<Empty JSON content>

How can I handle all these when I am getting the response

You can first check for empty response, and in try-catch try to parse array. If it's not array, it would throw exception that you can catch, and parse the Json object:

string resp; //this is where you will store your response from server
JArray array;
JObject json;
if(resp == "<Empty JSON content>")
{
   Console.WriteLine("Response is empty json");
}
else
{
   try
  {
    array = JArray.Parse(resp);
    Console.WriteLine("Array parsed");
  }
  catch (Newtonsoft.Json.JsonException ex)
  {
      try
      {
         json = JObject.Parse(resp);
         Console.WriteLine("error parsed");
      }
      catch(Newtonsoft.Json.JsonException ex2)
      {
         Console.WriteLine("Response was not json object");
      }        
  }
}

So, you want to handle those different types of responses depending on what you receive... Well, first you can go to json2csharp and auto generate the classes, if you haven't already.

Then you'll need to add those classes and you'll get something like this:

public class File
    {
        public class RootObject
        {
            public List<string> fileName { get; set; }
            public List<string> date { get; set; }
            public List<string> time { get; set; }
            public string id { get; set; }
            public int version_ { get; set; }
        }
    }

And in a different class:

public class Error
    {
        public class ValidationError
        {
            public string errorCode { get; set; }
            public string path { get; set; }
            public string apiMessage { get; set; }
        }

        public class RootObject
        {
            public string resultType { get; set; }
            public string errorType { get; set; }
            public string errorCode { get; set; }
            public string apiMessage { get; set; }
            public List<ValidationError> validationErrors { get; set; }
            public string requestId { get; set; }
        }
    }

So, now that you have the classes to deserialize the objects into, you need to add the json namespace to where you need to receive the json (if you can't find it just install the nugget Newtonsoft.Json):

using Newtonsoft.Json;

So, after you get your reponse JSON object, you can just deserialize it into a list of objects you created:

var file = JsonConvert.DeserializeObject>(response);

Since I'm not receiving those json objects I can't totally replicate it but you basically encapsulate this into a try catch block and should it throw any errors you'll know the object you received isn't of thtat type (File), but rather of the (Error) type so, after you catch the error you can do the same. And should happen the same thing on the Error object you'll know you didn't get anything.

Ping me if you have any doubts.

If you're getting 200 for both successful and unsuccessful calls, you may try to deserialize the response to dynamic , and then check the elements.

dynamic response = JsonConvert.DeserializeObject(json);

See a similar question here: Deserialize json in a "TryParse" way .

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