【问题标题】:JSON.net problem with JsonConvert.DeserializeObjectJsonConvert.DeserializeObject 的 JSON.net 问题
【发布时间】:2009-10-12 10:24:11
【问题描述】:

我有以下代码和json:

public class Labels
{
    public Labels()
    {}

    public Label[] Label {get;set;}
}

public class Label
{
    public Label()
    { }
    public string Name { get; set; }
    public int TorrentsInLabel { get; set; }
}

//...
Labels o = JsonConvert.DeserializeObject<Labels>(json);
//...


{"label": 
[
  ["seq1",1]
  ,["seq2",2]
]}

我希望这个数组 ["seq1","1"] 反序列化为 Label 对象。我错过了什么?一些属性?

当我运行时出现异常:预期类型为“test_JSONNET.Label”的 JsonArrayContract,得到了“Newtonsoft.Json.Serialization.JsonObjectContract”。

tnx

gg

【问题讨论】:

  • 你试过“反映”它吗?
  • JSON.net 是开源的,我现在正在查看代码,但目前还没有。
  • 建议:在开始查看源代码之前先浏览一下文档怎么样? (james.newtonking.com/projects/json/help)
  • 大部分文档都是从源代码自动生成的
  • 我完全同意!最好是参考。我一直在与完全相同的情况作斗争……默认(反)序列化程序不起作用,所以我们必须自己编写。对那个文档一点头绪都没有!

标签: c# json serialization json.net


【解决方案1】:

JsonConvert 怎么知道“seq1”对应name,“1”对应TorrentsInLabel?请看一下 JsonObjectAttribute、JsonPropertyAttribute、JsonArrayAttribute

【讨论】:

  • 你确定吗?它缺少合同而不是属性。我尝试将 JsonArrayAttribute 放在 Label 上,将 JsonPropertyAttrbiute 放在 Name 和 TorrentsInLabel 上,但这些属性需要属性名称。
  • 你是对的。似乎,最简单的方法是在 Label 中实现一些集合接口 - IList 或 ICollection。
  • 是的,但我想从 json 数组到业务对象。目前我正在通过继承 JsonCoverter 来实现解决方案,但它不会是完美的。
【解决方案2】:

默认情况下,类序列化为 JSON 对象,其中类的属性成为 JSON 对象的属性。

{
    Name: "seq",
    TorrentsInLabel: 1
}

您正在尝试将其序列化为一个数组,这不是 Json.NET 序列化程序默认工作的方式。

要获得你想要的,你应该创建一个 JsonConverter 并手动读写 JSON for Label 成为你想要的(一个数组)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多