简体   繁体   中英

How to manage two type of json in the same class?

I have this json structure:

[{"trace":{"details":{"date":"[28-02-2016 11:04:26.856573]","type":"[info]","message":"[system done.]"},"context":{"context":[[{"ID":"john dillinger"}]]}}},{"trace":{"details":{"date":"[28-02-2016 11:04:26.856728]","type":"[info]","message":"[trace done.]"},"context":{"context":[[{"ID":"john dillinger"}]]}}}]

I can deserialize it correctly using this class:

public class Trace
{
    public TraceValue trace;
}

public class TraceValue
{
    public Details details;
    public Context context;
}

public class Details
{
    public String date;
    public String type;
    public String message;
}

public class Context
{
    public List<List<IdItem>> context;
}

public class IdItem
{
    public String ID;
}

an example of deserialization:

var response = "json above";
var obj = JsonConvert.DeserializeObject<List<Trace>>(response);

now the problem is that sometimes the json is returned with this structure:

{
  "success": false,
  "message": "No content."
} 

my code fall in error 'cause the structure is different. I tried to read the header but is returned as 200 'cause no error happean. So how can I recognize the different structure and avoid the json exception? This is the class to manage the different json structure:

 public class RootObject
 {
      public bool success { get; set; }
      public string message { get; set; }
 }

I could do this in the exception but this isn't a good practice, there is another way?

In a case like yours, the better is to first obtain a JToken and then check if it has the message property and deserialize to the correct object:

var container = (JContainer)Newtonsoft.Json.JsonConvert.DeserializeObject(response);

var message = container["message"];

if(message == null)
{
    var obj = container.ToObject<List<Trace>>();

    //Do whatever you need to do with the object
}
else
{
    var msg = container.ToObject<RootObject>();

    //Do whatever you need to do with the object
}

Not a proper way but I have done this.

Convert the generated json object in to string. And edit the string to make the same format.

Than you can parse both string which are in same format

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