首页 > 解决方案 > 以数字为键反序列化 JSON

问题描述

我有这样的 JSON:

{
  "success": 1,
  "method": "getTrades",
  "5183": {
    "buy_amount": "0.00455636",
    "buy_currency": "BTC"
  },
  "6962": {
    "buy_amount": "52.44700000",
    "buy_currency": "IOT"
  },
  "6963": {
    "buy_amount": "383.54300000",
    "buy_currency": "TNT"
  },
  "6964": {
    "buy_amount": "3412.50000000",
    "buy_currency": "FUN"
  },
  "6965": {
    "buy_amount": "539.45000000",
    "buy_currency": "XLM"
  }
}

我需要将此 JSON 转换为域模型。

      public class Root {
       [JsonProperty("success")]
       public long Success { get; set; }
       [JsonProperty("method")]
       public string Method { get; set; }
       public Dictionary<long, Transaction> Transactions { get; set; }

      public class Transaction{
       [JsonProperty("buy_amount")]
       public decimal? BuyAmount { get; set; }
       [JsonProperty("buy_currency")]
       public string BuyCurrency { get; set; }

      var model = JsonConvert.DeserializeObject<Root>(response);

我创建了这两个模型,但是当我尝试反序列化事务时,它们为空。我得到了成功和方法的数据

标签: c#jsondeserialization

解决方案


要么 json 需要改变,要么你需要修改你的 c# 结构。不是 100% 确定,但基于 JSON,c# 类应该是

public class Root : Dictionary<long, Transaction> {
   [JsonProperty("success")]
   public long Success { get; set; }
   [JsonProperty("method")]
   public string Method { get; set; }

推荐阅读