在C#中反序列化Json的问题

时间:2014-12-03 04:51:24

标签: c# json json-deserialization

我有一些像这样的json:

{
    "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.statusadd.search_date ...等有值,但add.results为空。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

我认为问题是使用@type作为非法标识符。尝试在[DataMember(Name = "@type")]之前使用public string @type { get; set; }。在[DataContract]之前添加public class Address

因此,您的最终代码将是,

[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; }
}