在C#中读取动态JSON类型

时间:2019-06-06 06:51:58

标签: c# json

您可以找到整个json文件here

一小部分:

{
   "35891":[
      {
         "itemId":5021,
         "minAmount":1,
         "maxAmount":1000,
         "rate":100,
         "rarity":"ALWAYS",
         "announce":false
      },
      {
         "itemId":22374,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.033,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":22375,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.033,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":22376,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.033,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":20510,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.0066,
         "rarity":"RARE",
         "announce":true
      }
   ],
   "25084":[
      {
         "itemId":22729,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.0042,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":22730,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.0042,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":22731,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.0042,
         "rarity":"RARE",
         "announce":true
      },
      {
         "itemId":22732,
         "minAmount":1,
         "maxAmount":1,
         "rate":0.0042,
         "rarity":"RARE",
         "announce":true
      }
   ]
}

我主要希望能够从中获得每个“项目”。一个项目的示例是“ 35891”,我希望能够获得“ 35891”的数据。

我尝试了以下操作:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(readText, typeof(object));

还要使用常规的Json.Deserialize

读取数据后,我还希望能够写入(序列化)。

1 个答案:

答案 0 :(得分:1)

使用NewtonSoft.Json

public class Data
{
    public int itemId { get; set; }
    public int minAmount { get; set; }
    public int maxAmount { get; set; }
    public decimal rate { get; set; }
    public string rarity { get; set; }
    public bool announce { get; set; }
}

...

var result = JsonConvert.DeserializeObject<Dictionary<string, Data[]>>("your json here");