Json.Net反序列化JSON对象

时间:2017-11-14 15:48:00

标签: c# json json.net

我弹出使用WebServer返回Json波纹管,我无法将其转换为对象。

的Json

{
    "success":true,
    "data":{
        "24486146360":{
            "rfid":"123465789456",
            "products":[
            {
                "sale_id":35,
                "quantity":2,
                "price":"1",
                "total":"2",
                "unit":"uni",
                "sku":14
            },
            {
                "sale_id":36,
                "quantity":2,
                "price":"2.5",
                "total":"5",
                "unit":"uni",
                "sku":17
            }
            ]
        },
        "24758345953":{
            "rfid":"2129",
            "products":[
            {
                "sale_id":39,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "64577015900":{
            "rfid":"1934",
            "products":[
            {
                "sale_id":40,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "56768990934":{
            "rfid":"1746",
            "products":[
            {
                "sale_id":46,
                "quantity":1,
                "price":"8.00",
                "total":"8",
                "unit":"UN",
                "sku":20
            }
            ]
        }
    }
}

我使用json2sharp从JSON生成一个类,然后我清理了类,并留下了以下内容:

我的班级为json2sharp

创建帮助
public class Consumo
{
    public string rfid { get; set; }
    public List<ConsumoProduto> products { get; set; }
}

public class ConsumoProduto
{
    public int sale_id { get; set; }
    public double quantity { get; set; }
    public string price { get; set; }
    public string total { get; set; }
    public string unit { get; set; }
    public int sku { get; set; }
}

public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public List<Consumo> Registro { get; set; }
}

我的问题

如何使用Json.Net将Json转换为有效对象?

测试

我试图这样做而且我不能

Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);

1 个答案:

答案 0 :(得分:2)

RetornoConsumo课程中,Registro属性必须是Dictionary<string, Consumo>,而不是List<Consumo>

public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public Dictionary<string, Consumo> Registro { get; set; }
}

然后,您需要将JSON反序列化为RetornoConsumo类:

var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);

小提琴:https://dotnetfiddle.net/vfhdXp