在 C# 中反序列化 Json 时出现问题

本文关键字:问题 Json 反序列化 | 更新日期: 2023-09-27 18:32:50

>我有一些这样的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为空。

我的代码有什么问题?

在 C# 中反序列化 Json 时出现问题

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