Question background:
I am receiving a JSON response via a HttpResponseMessage, as shown:
var jsonString= response.Content.ReadAsStringAsync().Result;
This is giving me the following simple escaped JSON string result:
"\"{\\\"A\\\":\\\"B\\\"}\""
The problem:
I am using Newtonsoft to try and deserialize this to a model:
SimpleModel simpleModel= JsonConvert.DeserializeObject<SimpleModel>(jsonString);
The Class model of SimpleModel
:
public class SimpleModel
{
public string A { set; get; }
}
The conversion is giving me the following error:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Error converting value "{"A":"B"}" to type 'PyeWebClient.Tests.ModelConversionTests+SimpleModel'. Path '', line 1, position 15.
The JSON I receive back from the Task Result is valid, so I cannot understand what the problem is to cause the conversion error, what is the correct way to format the JSON string so it can be converted to its C# model type?
You json appears serialize
twice.
1) So you have to first deserialize into string and then again deserialize into your SimpleModel
like
string json = "\"{\\\"A\\\":\\\"B\\\"}\"";
string firstDeserialize = JsonConvert.DeserializeObject<string>(json);
SimpleModel simpleModel = JsonConvert.DeserializeObject<SimpleModel>(firstDeserialize);
Output:
2) If you don't want to deserialize twice then parse your json into JToken
and then again parse it into JObject
like
string json = "\"{\\\"A\\\":\\\"B\\\"}\"";
JToken jToken = JToken.Parse(json);
JObject jObject = JObject.Parse((string)jToken);
SimpleModel simpleModel = jObject.ToObject<SimpleModel>();
Output:
Question: How it will be serialize twice?
Answer: When you return your result from HttpResponseMessage
you successfully serialized your result and after reading this result from ReadAsStringAsync
then this method again serialize your result that already serialized.
you can just unescape the json string back to normal string and than use DeserializeObject
string jsonString = "\"{\\\"A\\\":\\\"B\\\"}\"";
jsonString = Regex.Unescape(jsonString); //almost there
jsonString = jsonString.Remove(jsonString.Length - 1, 1).Remove(0,1); //remove first and last qoutes
SimpleModel simpleModel = JsonConvert.DeserializeObject<SimpleModel>(jsonString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With