您可以使用自定義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.NET? –
但是,如果我嘗試反序列化到列表- ,JSON.NET抱怨說它不能填充數組 –
magol
好的讓我試試這個代碼,請稍候。 –