Newtonsoft 转义 JSON 字符串无法反序列化为对象

Newtonsoft escaped JSON string unable to deseralize to an object

问题背景:

我正在通过 HttpResponseMessage 收到 JSON 响应,如图所示:

var jsonString= response.Content.ReadAsStringAsync().Result;

这为我提供了以下简单的转义 JSON 字符串结果:

"\"{\\"A\\":\\"B\\"}\""

问题:

我正在使用 Newtonsoft 尝试将其反序列化为模型:

SimpleModel simpleModel= JsonConvert.DeserializeObject<SimpleModel>(jsonString);

SimpleModel的Class模型:

 public class SimpleModel
 {
     public string A { set; get; }
 }

转换时出现以下错误:

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.

我从任务结果中收到的 JSON 是有效的,所以我无法理解导致转换错误的问题是什么,格式化 [= 的正确方法是什么40=] 字符串,以便可以将其转换为其 C# 模型类型?

你json出现serialize两次。

1) 所以你必须先反序列化成字符串,然后再反序列化成你的 SimpleModel like

string json = "\"{\\"A\\":\\"B\\"}\"";

string firstDeserialize = JsonConvert.DeserializeObject<string>(json);

SimpleModel simpleModel = JsonConvert.DeserializeObject<SimpleModel>(firstDeserialize); 

输出:

2) 如果您不想反序列化两次,那么将您的 json 解析为 JToken 然后再次将其解析为 JObject 喜欢

string json = "\"{\\"A\\":\\"B\\"}\"";

JToken jToken = JToken.Parse(json);
JObject jObject = JObject.Parse((string)jToken);

SimpleModel simpleModel = jObject.ToObject<SimpleModel>();

输出:

问题:如何序列化两次?

答案: 当您 return 来自 HttpResponseMessage 的结果时,您成功序列化了您的结果,并且在阅读了来自 ReadAsStringAsync 的结果之后,这方法再次序列化您已经序列化的结果。

你可以将 json 字符串转义为普通字符串,然后使用 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);