I have this JSON that is generated by a third party web service
{
"user_data": {
"123456789": {
"transactions_id": 123456789,
"transaction_date": "2015-07-08T18:31:28+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"reward_name": " foo"
},
"1234567891": {
"transactions_id": 1234567891,
"transaction_date": "2015-07-08T18:33:06+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"reward_name": " foo"
},
"1234567892": {
"transactions_id": 1234567892,
"transaction_date": "2015-07-08T18:35:00+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"issuers_name": " foo"
}
}
}
The amount of transactions will change with each request so there may be 3 like this one time and then 10 the next. To handle the varying numbers of transactions I understand that you would need to use a list similar to this public List<User> users { get; set; }
with users being similar to this
public class User
{
public int transactions_id { get; set; }
public string transaction_date { get; set; }
public string reason_type { get; set; }
public string category { get; set; }
public string title { get; set; }
public string description { get; set; }
public int reward_quantity { get; set; }
public string reward_name { get; set; }
}
However I do think this will work because of the weird structure of the JSON where each "transaction" has it ID as its name. Sorry I'm not sure of the correct terminology but I think you should be able to get the gist.
This isn't a particularly unusual structure in JSON. That should be deserialized to a Dictionary<string, User>
:
public class Root
{
[JsonProperty("user_data")]
public Dictionary<string, User> Users { get; set; }
}
Then just use JsonConvert.DeserializeObject<Root>
as normal.
Note how I'm using JsonProperty
to specify how the name is represented in JSON while keeping idiomatic .NET property names - I suggest you do that in your User
class too.
See more on this question at Stackoverflow