Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to deserialize JSON?

Tags:

json

c#

asp.net

I am posting to an API that may return either 1 of the following 2 formats of JSON strings:

{
"MessageType": 6,
"Message": "Unable to SAVE new record. Invalid posted data."
}

or

{
"Model": {
    "Id": "1-6Q0RZ9",
    ...

         },   
"ResponseResult": {
    "MessageType": 10,
    "Message": "Successfully saved, Record Id = 1-6Q0RZ9"
                  }
}

I need to retrieve the results from MessageType and have tried every if condition I can think of to read the results, because the syntax or retrieving the key:value is different for each JSON string, and there are no other flags to trigger one or the other. So the code I used is:

string result = eml.PostData("API/Save", dataJSON.ToString());
var returnresult = new JavaScriptSerializer().Deserialize<dynamic>(result);
try {
  var responseresults = returnresult["ResponseResult"];
  rr = responseresults["MessageType"];
  rrtxt = responseresults["Message"];
} catch (Exception ex) {
  rr = returnresult["MessageType"];
  rrtxt = returnresult["Message"];
}

Which works great. If there is a valid Db post it returns the second JSON which is parsed correctly by the TRY statement, if not it throws a "key not found" error and parses the returned string in the CATCH statement (the first JSON example). Obviously this is horrible code but I cannot think of another way to do this, and I was wondering if anyone had suggestions? (please?)

Thanx in advance.

like image 854
Rick Bailly Avatar asked Aug 09 '13 19:08

Rick Bailly


1 Answers

How about deserializing the response to an object with all of the properties on each return type and then just checking the values?

public class ReturnObject
{
     public YourModel Model {get;set;}
     public ResultObject ResponseResult {get;set;}
     public int? MessageType {get;set;}
     public string Message {get;set;}
}


string result = eml.PostData("API/Save", dataJSON.ToString());
var returnresult = new JavaScriptSerializer().Deserialize<ReturnObject>(result);
{
  if(returnresult.MessageType.HasValue)
  {
     var messageType = returnResult.MessageType.Value;
     etc etc.
  }

} 
like image 193
bluetoft Avatar answered Sep 22 '22 06:09

bluetoft