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

标签 c# json json.net deserialization json-deserialization

问题背景:

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

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

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

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

问题:

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

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

SimpleModel的类模型:

 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 是有效的,所以我不明白导致转换错误的问题是什么,格式化 JSON 字符串以便将其转换为 C# 的正确方法是什么模型类型?

最佳答案

你的json出现了两次serialize

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

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

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

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

输出:

enter image description here

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

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

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

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

输出:

enter image description here

问题:如何序列化两次?

Answer: 当您从 HttpResponseMessage 返回结果时,您成功序列化了结果,在从 ReadAsStringAsync 读取结果后,此方法再次序列化您的结果已经序列化。

关于c# - Newtonsoft 转义 JSON 字符串无法反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095457/

相关文章:

c# - 扩展 Entity Framework 6 类

c# - 在 Xamarin Master-Detail MVVM 设置中,如何从 subview 的 View 模型中触发事件并让它被父 View 的 View 模型捕获

javascript - JSON.parse() 返回意外的输入结束

c# - 将 Newtosoft JObject 直接转换为 BsonDocument

c# - 反序列化 iso 8601 日期

c# - 循环遍历数组问题的内容

c# - 四舍五入到最接近的偶数分

json - 非隐式写入无法处理 Option(Scala、JSON、Play 2.3.6)

python - 如何将json数据从url打印到excel?

c# - 时区看似错误的 JSON ISO 日期