2014-12-03 160 views
0

我有一些JSON這樣的:問題與反序列化JSON在C#

{ 
    "status": "OK", 
    "result": { 
     "@type": "address_result__201301", 
     "barcode": "1301013030001010212212333002003031013", 
     "bsp": "044", 
     "dpid": "99033785", 
     "postcode": "4895", 
     "state": "QLD", 
     "suburb": "COOKTOWN", 
     "city": null, 
     "country": "AUSTRALIA" 
    }, 
    "search_date": "03-12-2014 15:31:03", 
    "search_parameters": {}, 
    "time_taken": 636, 
    "transaction_id": "f8df8791-531e-4043-9093-9f35881f6bb9", 
    "root_transaction_id": "a1fa1426-b973-46ec-b61b-0fe5518033de" 
} 

然後,我創建了一些類:

public class Address 
{ 
    public string status { get; set; } 
    public Result results { get; set; } 
    public string search_date { get; set; } 
    public SearchParameters search_parameters { get; set; } 
    public int time_taken { get; set; } 
    public string transaction_id { get; set; } 
    public string root_transaction_id { get; set; } 
} 

public class Result 
{ 
    public string @type { get; set; } 
    public string barcode { get; set; } 
    public string bsp { get; set; } 
    public string dpid { get; set; } 
    public string postcode { get; set; } 
    public string state { get; set; } 
    public string suburb { get; set; } 
    public string city { get; set; } 
    public string country { get; set; } 
} 

public class SearchParameters 
{ 
} 

最後,我用這些代碼來獲得JSON數據:

string result = "Above json"; 
JavaScriptSerializer json = new JavaScriptSerializer(); 
Address add = json.Deserialize<Address>(result); 

我看到,add.status, add.search_date ...等有價值,但add.results爲空。

我的代碼有什麼問題?

+3

字段名和屬性名不匹配。 「結果」與「結果」。 – pickypg 2014-12-03 04:54:05

+0

我認爲問題是使用'@ type'作爲非法標識符。在public String @type {get;}之前嘗試使用'[DataMember(Name =「@type」)]''組; }'。在「公共類地址」之前添加一個[DataContract]。 – 2014-12-03 04:58:40

回答

0

我認爲問題是使用@type作爲非法標識符。嘗試在public string @type { get; set; }之前使用[DataMember(Name = "@type")]。在public class Address之前添加[DataContract]

因此,您的最終代碼會,

[DataContract] 
public class Result 
{ 
    [DataMember(Name = "@type")] 
    public string @type { get; set; } 
    public string barcode { get; set; } 
    public string bsp { get; set; } 
    public string dpid { get; set; } 
    public string postcode { get; set; } 
    public string state { get; set; } 
    public string suburb { get; set; } 
    public string city { get; set; } 
    public string country { get; set; } 
}