包含空格的JSON到C#类名

时间:2017-04-24 05:33:37

标签: c# json api ssis script-component

我从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 __” 时。我的解析但是在运行时会抛出“对象引用未设置为对象的实例”错误。

我的问题是,如何在不删除空格的情况下获取数据,我如何对此进行定律处理?

1 个答案:

答案 0 :(得分:1)

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

然后使用data annotation让模型绑定器识别它。

示例:

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"
        }
    ]
}

它应该有用。