Deserialize JSON array with different types

倾然丶 夕夏残阳落幕 提交于 2020-04-13 06:15:13

问题


I'm new to JSON.NET, and I need help to deserialize the following JSON

{
   "items": [
      [10, "file1", "command 1"],
      [20, "file2", "command 2"],
      [30, "file3", "command 3"]
   ]
}

to this

IList<Item> Items {get; set;}

class Item
{
   public int    Id      {get; set}
   public string File    {get; set}
   public string Command {get; set}
}

The content in the JSON is always in the same order.


回答1:


You can use a custom JsonConverter to convert each child array in the JSON to an Item. Here is the code you would need for the converter:

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

With the above converter, you can deserialize into your classes easily as demonstrated below:

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

Output:

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




回答2:


For deserialization your JSON should be like this

{
   "items": [
      {Id: 10, File: "file1", Command: "command 1"},
      {Id: 20, File: "file2", Command: "command 2"},
      {Id: 30, File: "file3", Command: "command 3"}
   ]
}

This will map the variables Id, File and Command to properties Id, File and Command respectively during deserialization

You can deserialize it using the following code

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



回答3:


You can do this by using an intermediate type to capture the conversion from Json and the map that to your Item class afterwards. So first we have the intermediate class:

public class IntermediateType
{
    public object[][] items { get; set; }
}

And now we can get your results like this:

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


来源:https://stackoverflow.com/questions/29695910/deserialize-json-array-with-different-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!