简体   繁体   中英

Deserializing JSON with numbers as key

I have JSON like this:

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

I need to convert this JSON to domain model.

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

I created these two models, but when I try to deserialize transactions, they are null. I got data for success and method

Either the json needs to change, or you need to modify your c# structures. Not 100% sure, but based on the JSON, the c# class should be

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

Can you change the JSON to something like this?

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

Then you could do something like that:

    public class Transaction    {
        public int id { get; set; } 
        public string buy_amount { get; set; } 
        public string buy_currency { get; set; } 
    }

    public class Root    {
        public int success { get; set; } 
        public string method { get; set; } 
        public List<Transaction> transaction { get; set; } 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM