Search code examples
c#jsondeserializationjson-deserialization

C# How do I correctly deserialize multiple custom objects in an array to an object?


I am retrieving a json object with an array, which contains multiple object types.

Given I retrieve a JSON payload that looks like this:

{
   "Lines": [
   {
       "PropertyA": "A",
       "PropertyB": "B"
   },
   {
       "Property01": 1,
       "Property02": 2
   }]
}

I want to deserialize this into a single object list.

Example:

public List<Line> Lines;

So I can compare the object with one I expect.

What I have so far:

public class Class1
{
    public string PropertyA = "A";
    public string PropertyB = "B";
}

public class Class2
{
    public int Property01 = 01;
    public int Property02 = 02;
}

public class MainClass
{
    public List<dynamic> Lines;
}

class Program
{
    static void Main(string[] args)
    {
        string json = "{\r\n \"Lines\": [\r\n {\r\n \"PropertyA\": \"A\",\r\n \"PropertyB\": \"B\"\r\n },\r\n {\r\n \"Property01\": 1,\r\n \"Property02\": 2\r\n }]\r\n}";

        MainClass actual = JsonConvert.DeserializeObject<MainClass>(json);

        MainClass expected = new MainClass()
        {
            Lines = new List<dynamic>()
            {
                new Class1(),
                new Class2()
            }
        };

        actual.Should().BeEquivalentTo(expected);
    }
}   

Any help would be greatly appreciated!

Cheers


Solution

  • You can verify the propriety name and deserialize in right object like that

    class Program
    {
        static void Main(string[] args)
        {
    
            var class1List = new List<Class1>();
            var class2List = new List<Class2>();
            var genericList = new List<dynamic>();
    
            var actual = JsonConvert.DeserializeObject<dynamic>(json);
            foreach (var item in actual.Lines)
            {
    
                string itemJson = JsonConvert.SerializeObject(item);
                if (itemJson.Contains("PropertyA"))
                {
                    var class1 = JsonConvert.DeserializeObject<Class1>(itemJson);
                    class1List.Add(class1);
                    genericList.Add(class1);
                }
                else
                {
                    var class2 = JsonConvert.DeserializeObject<Class2>(itemJson);
                    class2List.Add(class2);
                    genericList.Add(class2);
                }
            }
        }
    }
    
    public class Class1
    {
        public string PropertyA;
        public string PropertyB;
    }
    
    public class Class2
    {
        public int Property01;
        public int Property02;
    }