4

我有以下代码和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

4

2 回答 2

3

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

于 2009-10-12T10:46:29.683 回答
2

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

{
    Name: "seq",
    TorrentsInLabel: 1
}

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

To get what you want you should create a JsonConverter and read and write the JSON for Label manually to be what you want it to be (an array).

于 2009-10-16T23:16:55.940 回答