c# - 反序列化不同类型的JSON数组

标签 c# json.net

我是 JSON.NET 的新手,我需要帮助来反序列化以下 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 中的内容始终保持相同的顺序。

最佳答案

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

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

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

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

fiddle :https://dotnetfiddle.net/RXggvl

关于c# - 反序列化不同类型的JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29695910/

相关文章:

c# - 在 T4 代码生成中,如何从引用的程序集中获取类型?

c# - 如何在不使用 `DisplayNameAttribute` 的情况下更改 ViewModel 显示名称?

c# - 反序列化 json 对象并将内部对象转换为字符串值?

SelectTokens中的JSON.Net "Could not read query operator"

c# - Json.Net 两次没有以相同的方式序列化小数

c# - 从 C# 到非托管 C++ 库中执行 DllImport 时出现 MSBuild 4.0 依赖性问题

c# - 如何测试这个简单的索引方法?

c# - 验证元素的未转义长度

serialization - 无法反序列化 ClaimPrincipal

c# - 与 wcf REST 通信的 JSON.NET 兼容序列化