2009-10-12 96 views
4

我有以下代码和JSON:JSON.net问题JsonConvert.DeserializeObject

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

+0

你试过“反映了”吗? – 2009-10-12 10:32:18

+0

JSON.net是开源的,我现在正在通过代码,但没有到目前为止。 – 2009-10-12 10:33:35

+0

建议:在开始查看源代码之前,如何查看一些文档? (http://james.newtonking.com/projects/json/help/) – Svish 2009-10-12 10:54:46

回答

2

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

{ 
    Name: "seq", 
    TorrentsInLabel: 1 
} 

你试图序列化它到一个数组,这不是默认情况下Json.NET串行器的工作方式。

为了得到你想要的,你应该创建一个JsonConverter和读写标签的JSON手动是你希望它是(数组)什么什么。

3

JsonConvert怎么能知道 “SEQ1” 对应的名称, “1” 对应的TorrentsInLabel?请查看JsonObjectAttribute,JsonPropertyAttribute,JsonArrayAttribute

+0

你确定吗?它缺少Contract not Attribute。我试着把JsonArrayAttribute放在Label和JsonPropertyAttrbiute上Name和TorrentsInLabel,但是这些属性需要属性名称。 – 2009-10-13 06:45:35

+0

你说得对。看来,最简单的方法是在Label - IList或ICollection中实现一些收集界面。 – darkiri 2009-10-13 08:33:16

+0

是的,但我想从JSON数组到业务对象。 目前我通过继承JsonCoverter实施的解决方案,但它不会是完美的。 – 2009-10-13 09:14:55