使用id作为键反序列化JSON对象结构

时间:2015-09-13 17:48:03

标签: c# json list json.net deserialization

我有这个由第三方Web服务生成的JSON

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

交易金额会随着每个请求而变化,因此可能会有3次像这样一次,然后是10次。为了处理不同数量的交易,我了解您需要使用类似于此public List<User> users { get; set; }的列表,用户与此类似

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; }
}

但是我确实认为这会起作用,因为JSON的结构很奇怪,每个“事务”都有ID作为名称。对不起,我不确定正确的术语,但我认为你应该能够获得要点。

2 个答案:

答案 0 :(得分:6)

这在JSON中并不是一个特别不寻常的结构。应将其反序列化为Dictionary<string, User>

public class Root
{
    [JsonProperty("user_data")]
    public Dictionary<string, User> Users { get; set; }
}

然后正常使用JsonConvert.DeserializeObject<Root>

请注意我是如何使用JsonProperty指定名称在JSON中的表示方式,同时保留惯用的.NET属性名称 - 我建议您也在User类中执行此操作。

答案 1 :(得分:1)

public class UserData
{
    [JsonProperty("user_data")]
    public Dictionary<string, User> Users { get; set; }
}