gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:06:46 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com