【问题标题】:JSON.NET Failing Deserialization of a Seemingly Valid JSON BlobJSON.NET 对看似有效的 JSON Blob 的反序列化失败
【发布时间】:2015-04-27 20:59:45
【问题描述】:

我有一个从服务返回的 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);

我收到以下错误:

将值转换为类型时出错 'System.Collections.Generic.List`1[Beem.StationModels.Station]'。小路 '',第 1 行,位置 29904。

其中 29904 是从服务获取的 JSON 字符串中的最后一个字符。

Station 类配备了正确的 JSON 属性绑定,并具有默认构造函数。

我在这里错过了什么?

【问题讨论】:

  • JSON 是否通过jsonlint
  • 我能够成功反序列化您的 JSON。你确定字符串真的有两个反斜杠,比如:"Value\\ of the string."?或者字符串是否只有一个反斜杠,而 Visual Studio 在显示时会“帮助”转义它,如下所示:"Value\ of the string."
  • 你能显示Station类吗?
  • 上面的 JSON 是一个测试 blob,它不是真正的 JSON。该字符串确实有两个反斜杠,它通过 JSONLint。

标签: c# .net json serialization json.net


【解决方案1】:

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

【讨论】:

  • 就像我提到的,上面的字符串只是一个示例。想象一下相同的数据桶,但可能重复了 60 次。出于某种原因,它只是不想处理数据,即使是JArray
  • 另外,是的,我的Station 课程遵循与您上述相同的模式。
猜你喜欢
  • 2015-05-21
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多