【问题标题】:Reading dynamic json types in c#在 C# 中读取动态 json 类型
【发布时间】:2019-06-06 06:51:58
【问题描述】:

你可以找到整个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

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

【问题讨论】:

标签: c# json


【解决方案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");

【讨论】:

  • Newtonsoft.Json.JsonReaderException: '无法将字符串转换为整数:总是。路径 '35891[0].rarity',第 8 行,位置 24。'
  • @Kyle 固定数据类
  • 这行得通,但我不能 var result = JsonConvert.DeserializeObject>(readText); MessageBox.Show((result[0]).ToString());
  • @Kyle 这是一本字典,所以用它当字典吧。
  • nvm 想通了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2013-04-09
相关资源
最近更新 更多