我有一个从服务返回的 JSON blob,随后我将其转换为字符串。
然后,如果我为字符串在变量中的存储位置设置断点,我就可以在 Visual Studio JSON Visualizer 中轻松查看该字符串:
值得一提的是,JSON 数据包含大量转义字符,这些字符再次在 JSON Visualizer 中正确呈现。
我得到的 JSON blob 遵循以下模式:
[
{
"property" : "Value",
"property2" : "Value\\ of the string."
},
{
"property" : "ValueX",
"property2" : "ValueY\\ of the string."
}
]
当我开始反序列化过程时,使用以下代码:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Include;
settings.StringEscapeHandling = StringEscapeHandling.Default;
List<Station> deserializedYaps = JsonConvert.DeserializeObject<List<Station>>(data, settings);
我收到以下错误:
Error converting value to type 'System.Collections.Generic.List`1[Beem.StationModels.Station]'. Path '', line 1, position 29904.
其中 29904 是从服务获取的 JSON 字符串中的最后一个字符。
Station
类配备了正确的 JSON 属性绑定(bind)并具有默认构造函数。
我在这里错过了什么?
最佳答案
Newtonsoft Json 4.0.5.0 做得很好,假设站类如下所示:
public class Station
{
public object Property { get; set; }
public object Property2 { get; set; }
}
你可以这样测试:
sb.AppendLine("[");
sb.AppendLine(" {");
sb.AppendLine(" \"property\" : \"Value\",");
sb.AppendLine(" \"property2\" : \"Value\\\\ of the string.\"");
sb.AppendLine(" },");
sb.AppendLine(" {");
sb.AppendLine(" \"property\" : \"ValueX\",");
sb.AppendLine(" \"property2\" : \"ValueY\\\\ of the string.\"");
sb.AppendLine(" }");
sb.AppendLine("]");
var json = sb.ToString();
var settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Include};
var deserializedYaps = JsonConvert.DeserializeObject<List<Station>>(json, settings);
关于c# - 看似有效的 JSON Blob 的 JSON.NET 反序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726270/