2017-04-24 42 views
1

我從一個API請求JSON的C#類名稱用空格

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

返回以下JSON類當我使用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

嗯,這顯然是空的,因爲你已經改變了屬性名稱,因此它沒有被填充 - 我不明白這與問題有什麼關係。檢查序列化庫的文檔,瞭解如何將屬性映射到不同的JSON屬性名稱。可能涉及添加屬性。 – Rob

+0

試着問這個服務的老闆 - mailto:[email protected] – anatol

回答

0

嘗試先使用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" 
     } 
    ] 
} 

它應該工作。

+0

真棒謝謝。這正是我所苦苦掙扎的。 –

相關問題