Best way to deserialize JSON?

I am posting to an API that can return one of the following two JSON string formats:

{ "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 get the results from MessageType and try every condition that I can come up with to read the results, because the syntax or getting the key: value for each JSON string is different and there are no other flags to start one or the other. So I used the code:

 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 message, it returns a second JSON, which is correctly parsed into the TRY statement, if it does not throw a "key not found" error, and parses the returned string in the CATCH statement (first JSON example). This is obviously awful code, but I can't think of another way to do this, and I was wondering if anyone has any suggestions? (You are welcome?)

Thanx in advance.

+6
source share
1 answer

How about deserializing the response to an object with all the properties for each type of return value, 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. } } 
+1
source

Source: https://habr.com/ru/post/951417/


All Articles