我是 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
小提琴:https://dotnetfiddle.net/RXggvl
对于反序列化,您的 JSON 应该是这样的
{
"items": [
{Id: 10, File: "file1", Command: "command 1"},
{Id: 20, File: "file2", Command: "command 2"},
{Id: 30, File: "file3", Command: "command 3"}
]
}
这将在反序列化期间分别映射variables Id, File and Command to properties Id, File and Command
您可以使用以下代码反序列化它
public List<Item> DeserializeJSON(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Item>));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var obj = (List<Item>)ser.ReadObject(stream);
return obj;
}
您可以使用中间类型捕获从 Json 的转换,然后将其映射到Item
类。所以首先我们有中间类:
public class IntermediateType
{
public object[][] items { get; set; }
}
现在我们可以得到这样的结果:
var json = "{"items": [ [10, "file1", "command 1"], [20, "file2", "command 2"], [30, "file3", "command 3"] ]}";
var result = JsonConvert
.DeserializeObject<IntermediateType>(json)
.items
.Select(o => new Item
{
Id = int.Parse(o[0].ToString()),
File = (string)o[1],
Command = (string)o[2]
});