2

我从 API 请求返回以下 JSON 类

"Top Uncommitted Spend": [
                {
                  "AccountID": 99999991,
                  "H1": "Liabilities",
                  "H2": "Top Uncommitted Spend",
                  "H3": "",
                  "SH1": "",
                  "Description": "FUEL (ATM,ATM FEE)",
                  "Count": 4,
                  "FrequencyDescription": "Mostly 17 Days",
                  "FrequencyDuration": "Ongoing",
                  "FrequencyDurationDate": "11Aug - 30Sep",
                  "FrequencyWeekday": "",
                  "FrequencyAmount": 116,
                  "FrequencyAmountRange": "(2-280)",
                  "TotalAmount": 464,
                  "TotalInAmount": 0,
                  "TotalOutAmount": 464,
                  "MonthlyAmount": 305.5481,
                  "GroupID": "128081-1241",
                  "Display": "FUEL",
                  "FrequencyExactness": "Mostly",
                  "FrequencyPeriod": "17 Days",
                  "ScoreEmployer": null,
                  "ScoreDirCr": null,
                  "ScoreWeekday": null,
                  "ScoreFrequency": null,
                  "ScoreAmount": null,
                  "ScoreTotal": 0
                },

当我使用 json2csharp 生成我的类时,我得到了这个,因为标签的名称中有空格。

    public class Liabilities
{
    public List<Rent> Rent { get; set; }
    public List<Periodic> Periodic { get; set; }
    public List<NonPeriodic> __invalid_name__Non-Periodic { get; set; }
    public List<TopUncommittedSpend> __invalid_name__Top Uncommitted Spend { get; set; }
}

当我删除“__invalid_name__”从名字。我的解析但是在运行时会引发“对象引用未设置为对象的实例”错误。

我的问题是我如何对此进行反序列化以便在不删除空格的情况下取出数据?

4

1 回答 1

2

尝试首先使用json2csharp删除空格以获取有效的 c# 类。

然后使用数据注释让模型绑定器识别它。

例子:

public class Liabilities
{
    //removed other collections for simplicity
    [JsonProperty(PropertyName = "Top Uncommitted Spend")]  // <-- *add this*
    public List<TopUncommittedSpend> TopUncommittedSpend { get; set; }
}

public class TopUncommittedSpend
{
    public int AccountID { get; set; }
    public string H1 { get; set; }
    public string H2 { get; set; }
    //removed for simplicity
}

现在,如果您使用以下内容向您的 api 控制器发布帖子:

{
    "Top Uncommitted Spend": [{
            "AccountID": 99999991,
            "H1": "Liabilities",
            "H2": "Top Uncommitted Spend"
        }
    ]
}

它应该工作。

于 2017-04-24T06:09:38.097 回答