Newtonsoft escaped JSON string unable to deseralize to an object

浪子不回头ぞ 提交于 2019-12-23 02:03:04

问题


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?


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/52095457/newtonsoft-escaped-json-string-unable-to-deseralize-to-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!