Reputation: 423
I am returning the following JSON Class from an API Request
"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
},
When I use json2csharp to generate my class I get this because the tag has spaces in the name.
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; }
}
When I remove the "__invalid_name__" and the from the name. My parses but when run it throws an "Object reference not set to an instance of an object" error.
My question is how do I derseriaise this in order to get the data out without removing the spaces?
Upvotes: 3
Views: 3446
Reputation: 829
Try removing the spaces to get a valid c# class using json2csharp first.
Then use data annotation to get the model binder to recognise it.
Example:
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
}
Now if you do a post to your api controller using the below:
{
"Top Uncommitted Spend": [{
"AccountID": 99999991,
"H1": "Liabilities",
"H2": "Top Uncommitted Spend"
}
]
}
It should work.
Upvotes: 3