2013-06-04 67 views
1

我使用Json.NET反序列化JSON如下:屬性爲null

[ 
    { 
     "id": 1234, 
     "name": "Example", 
     "coords": "[12:34]", 
     "relationship": "ownCity" 
    }, 
    { 
     "id": 53, 
     "name": "Another example", 
     "coords": "[98:76]", 
     "relationship": "ownCity" 
    } 
] 

我試圖把它解析到一個列表。

List<City> cities = JsonConvert.DeserializeObject<List<City>>(json); 

城市類的definiton:

public class City 
{ 
    int id { get; set; } 
    string name { get; set; } 
    string coords { get; set; } 
    string relationship { get; set; } 
} 

結果是兩個城市對象的名單,但他們所有的屬性都爲空(ID爲0)。

任何人都可以給我一個頭,我做錯了什麼?提前致謝。

+0

只要你知道,id爲0,因爲整數缺省值是0,其中作爲一個字符串是一個引用類型,他們將爲空:) –

回答

3

您的字段全部標記爲(默認)爲私有。 其更改爲公共或受保護的,它應該很好地工作:

public class City 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    public string coords { get; set; } 
    public string relationship { get; set; } 
} 
+0

哦,上帝,我是愚蠢的。謝謝! – nXu

1

它會爲你工作

  • 您需要添加公共訪問級別

類成員的訪問級別和結構成員(包括嵌套類和結構體)在默認情況下是私有的。

  • 或 您需要DataContractAttribute類和DataMemberAttribute屬性到您要序列化的成員。作爲一個沒有[數據成員],你不能序列化非公共屬性或字段

[DataContract] 公共類城市 {

[DataMember] 
public int id { get; set; } 

    [DataMember] 
    public string name { get; set; } 

    [DataMember] 
    public string coords { get; set; } 

    [DataMember] 
    public string relationship { get; set; } 
}