反序列化具有不同类型的JSON数组 [英] Deserialize JSON array with different types

查看:108
本文介绍了反序列化具有不同类型的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON.NET的新手,我需要帮助反序列化以下JSON

I'm new to JSON.NET, and I need help to deserialize the following JSON

{
   "items": [
      [10, "file1", "command 1"],
      [20, "file2", "command 2"],
      [30, "file3", "command 3"]
   ]
}

对此

IList<Item> Items {get; set;}

class Item
{
   public int    Id      {get; set}
   public string File    {get; set}
   public string Command {get; set}
}

JSON中的内容始终是相同的顺序.

The content in the JSON is always in the same order.

推荐答案

您可以使用自定义JsonConverter将JSON中的每个子数组转换为Item.这是转换器所需的代码:

You can use a custom JsonConverter to convert each child array in the JSON to an Item. Here is the code you would need for the converter:

class ItemConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Item));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);
        return new Item
        {
            Id = (int)array[0],
            File = (string)array[1],
            Command = (string)array[2]
        };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

使用上述转换器,您可以轻松地反序列化到您的类中,如下所示:

With the above converter, you can deserialize into your classes easily as demonstrated below:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
           ""items"": [
              [10, ""file1"", ""command 1""],
              [20, ""file2"", ""command 2""],
              [30, ""file3"", ""command 3""]
           ]
        }";

        Foo foo = JsonConvert.DeserializeObject<Foo>(json, new ItemConverter());

        foreach (Item item in foo.Items)
        {
            Console.WriteLine("Id: " + item.Id);
            Console.WriteLine("File: " + item.File);
            Console.WriteLine("Command: " + item.Command);
            Console.WriteLine();
        }
    }
}

class Foo
{
    public List<Item> Items { get; set; }
}

class Item
{
    public int Id { get; set; }
    public string File { get; set; }
    public string Command { get; set; }
}

输出:

Id: 10
File: file1
Command: command 1

Id: 20
File: file2
Command: command 2

Id: 30
File: file3
Command: command 3

提琴: https://dotnetfiddle.net/RXggvl

这篇关于反序列化具有不同类型的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆