c# - 看似有效的 JSON Blob 的 JSON.NET 反序列化失败

标签 c# .net json serialization json.net

我有一个从服务返回的 JSON blob,随后我将其转换为字符串。

然后,如果我为字符串在变量中的存储位置设置断点,我就可以在 Visual Studio JSON Visualizer 中轻松查看该字符串:

enter image description here

值得一提的是,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/

相关文章:

javascript - 使用 javascript 从 ASPX 代码隐藏页面访问类

.net - 哪些代码控制 WPF 应用程序的启动?

.net - 为什么 .Net 在构建程序集时关心?

java - 记忆一个 Activity

c# - 使用单个并行 for 循环获取 Min、Max、Sum

c# - 用 LINQ 查询替换 foreach

c# - 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List` 1

javascript - 试图访问一个 json 字段

c# - GetResourceSet 不加载回退值

.net - 在创建简单的消息总线时,推荐的架构是什么?