Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft escaped JSON string unable to deseralize to an object

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?

like image 522
Dev Avatar asked Dec 11 '22 05:12

Dev


2 Answers

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:

enter image description here

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:

enter image description here

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.

like image 144
er-sho Avatar answered Dec 12 '22 19:12

er-sho


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);
like image 43
styx Avatar answered Dec 12 '22 17:12

styx