我是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中的内容始终采用相同的顺序。
答案 0 :(得分:4)
您可以使用自定义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
答案 1 :(得分:0)
对于反序列化,您的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;
}
答案 2 :(得分:0)
您可以使用中间类型来捕获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]
});