Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON array with different types

Tags:

c#

json.net

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.

like image 644
magol Avatar asked Apr 17 '15 09:04

magol


1 Answers

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

like image 192
Brian Rogers Avatar answered Nov 18 '22 05:11

Brian Rogers