c# JSON.net反序列化

本文关键字:反序列化 net JSON | 更新日期: 2023-09-27 18:11:36

昨天是我第一天遇到JSON,我发现的大多数例子都是JSON有像

这样的格式
{ "key1": "value1", "key2": "value2", ... }

但我有json字符串:

{"items":[[24,68,216,34006,32224],[68,177,277,140,2130], |...skip big amount of data....| ,[79606,8500392,0,0,14]],"updated":1475686082000,"columns":["id","buy","sell","supply","demand"]}

我试图弄清楚如何阅读这个并获得特定数量的数据。例如,我需要在列"买"answers"卖"的特定id的数字。

c# JSON.net反序列化

根据你的json你的模型应该是

public class YourRootObject
{
    public List<List<int>> items { get; set; }
    public long updated { get; set; }
    public List<string> columns { get; set; }
}

现在可以反序列化为

var obj = JsonConvert.DeserializeObject<YourRootObject>(json);

但是,为了不处理"更新"的值,我将更改模型如下,并编写一个json转换器。

public class YourRootObject
{
    public List<List<int>> items { get; set; }
    public DateTime updated { get; set; }
    public List<string> columns { get; set; }
}
public class EpochToDatetimeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var l = (long)reader.Value;
        return new DateTime(1970, 1, 1).AddMilliseconds(l).ToLocalTime();
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

现在可以反序列化为

var obj = JsonConvert.DeserializeObject<YourRootObject>(json, 
                                           new EpochToDatetimeConverter());

正如@Alex在评论中所说:

就读取而言,包含在[]中的任何内容都被视为数组。items字段是一个数组包含数组

如果你不想要这个数组的数组,你可以创建一个新的类来封装内部数组。例如:

{
  "items":
    [
      { "numbers": [24,68,216,34006,32224] },
      { "numbers": [68,177,277,140,2130] }, 
      |...skip big amount of data....| ,
      { "numbers": [79606,8500392,0,0,14]],
    ],
  "updated": 1475686082000,
  "columns": [ "id", "buy", "sell", "supply", "demand"]
}

你在c#中的类应该是:

public class Parent
{
  public List<Child> items;
  public int updated;
  public string[] columns;
  public Parent()
  {
    items = new List<Child>();
  }
}
public class Child
{
  public string[] numbers;
}

差不多。