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.
source share