Json.NET DeserializeObject将对象命名为1类

时间:2016-03-26 18:40:13

标签: c# json.net

我通过rest api从第三方供应商那里消费数据。

api返回的JSON片段:

{
    "invoice": {
        "id": "12345",
        "lines": {
            "line1": {
                "amount": 1,
                "amount_desc": "",
                "description": "Description 1",
                "tax_rate": "-1",
                "price": "100",
                "discount_pct": 0,
                "linetotal": 100
            },
            "line2": {
                "description": "Description 2"
            },
            "line3": {
                "amount": 1,
                "amount_desc": "",
                "description": "Description 3",
                "tax_rate": "-1",
                "price": "300",
                "discount_pct": 0,
                "linetotal": 300
            },
            "line4": {
                "description": "Description 4"
            }
        }
    }
}

我不知道有多少"线" API可以返回,因此我不想为每个行对象创建类。

我的" Line"课程看起来像:

public class Lines
{
    public Line Line1 { get; set; }
    public Line Line2 { get; set; }
    public Line Line3 { get; set; }
    public Line Line4 { get; set; }
}

public class Line
{
    public int Amount { get; set; }
    [JsonProperty("Amount_Desc")]
    public string AmountDesc { get; set; }
    public string Description { get; set; }
    [JsonProperty("Tax_Rate")]
    public string TaxRate { get; set; }
    public string Price { get; set; }
    [JsonProperty("Discount_Pct")]
    public int DiscountPct { get; set; }
    public int Linetotal { get; set; }
}

如何反序列化所有Line1,Line2,Line100?到我的单身" Line"类?

2 个答案:

答案 0 :(得分:1)

您可以将其反序列化为Dictionary<string, Line>

public class Invoice
{
    public string Id
    { get; set; }

    public Dictionary<string, Line> Lines
    { get; set; }
}

public class Data
{
    public Invoice Invoice
    { get; set; }
}

然后,您可以将问题中的JSON反序列化为仅包含Data属性的Invoice对象。那个Invoice属性属于Invoice类型,其中包含Lines字典中的行。

line1line4字符串成为字典中的键,值是反序列化的Line个对象。

答案 1 :(得分:0)

这里最大的问题是API返回的json做得非常糟糕。线应该是一个线数组,而不是一个有N行的对象。这将是正确的json:

{
    "invoice" : {
        "id" : "12345",
        "lines" : [{
                "amount" : 1,
                "amount_desc" : "",
                "description" : "Description 1",
                "tax_rate" : "-1",
                "price" : "100",
                "discount_pct" : 0,
                "linetotal" : 100
            }, {
                "description" : "Description 2"
            }, {
                "amount" : 1,
                "amount_desc" : "",
                "description" : "Description 3",
                "tax_rate" : "-1",
                "price" : "300",
                "discount_pct" : 0,
                "linetotal" : 300
            }, {
                "description" : "Description 4"
            }
        ]
    }
}

我认为要求他们更正他们的API将是最好的方式(双方)。