I'm attempting to deserialize a response from a REST API using JSON.NET.
dynamic resultObject = JsonConvert.DeserializeObject(responseText);
I'd like to not have to define classes for the different kinds of responses the REST API returns, as it changes often. I'd like to take advantage of dynamic runtime variables.
In VS2015, I've added watchers to see the values directly after the line of code above executes.
resultObject resolves to a null object, however, the watcher shows that the line code run directly results in aNewtonsoft.Json.Linq.JObject which is populated with the deserialized response string.
Why doesn't the dynamic var resultObject populate with the JObject?
var responseStream = e.Response?.GetResponseStream();
string responseText = "";
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
dynamic responseObject = JsonConvert.DeserializeObject(responseText);
foreach (var error in responseObject["errors"].Children())
{
errors.Add(error.Val);
}
}
UPDATE:
Contents of the JSON to parse:
JSON updated to remove debug information - problem persists.
https://jsonblob.com/57cb00c7e4b0dc55a4f2abe9
UPDATE 2:
It appears that JsonConvert.DeserializeObject() is parsing my JSON to have extra brackets around the entire object.
String as it is generated from the response stream:
"{\"message\":\"422 Unprocessable Entity\",\"errors\":[[\"The email must be a valid email address.\"],[\"The password must be at least 8 characters.\"]],\"status_code\":422}"
value of JsonConvert.DeserializeObject():
{{
"message": "422 Unprocessable Entity",
"errors": [
[
"The email must be a valid email address."
],
[
"The password must be at least 8 characters."
]
],
"status_code": 422
}}
UPDATE 3:
Converting to JObject.Parse resulted in the same output.
I changed the variable from type dynamic to JObject - to accept the response from JObject.Parse() and still the variable is set to null.