问题与反序列化JSON在C#

问题与反序列化JSON在C#

问题描述:

我有一些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

我认为问题是使用@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; } 
}