theateist
theateist

Reputation: 14411

How to deserialize json string to list of objects which type I get at runtime?

I want to deserialize json string to list of objects which type I get at runtime.

For example:

my json string is [{"id":"1", "name":"test"},{"id":"2", "name":"test2"}] and the type I get is "Types.type1, types.dll", so I need to deserialize it to List<type1>. If I will get the type "Types.type2, types.dll" so I need to deserialize it to List<type2>

How I can do this?

Upvotes: 1

Views: 735

Answers (1)

Aliostad
Aliostad

Reputation: 81680

You may use DataContractJsonSerializer in System.Runtime.Serialization

public class Foo
{
    public string Bar { get; set; }
    public int Baaz { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Foo>));
        MemoryStream ms = new MemoryStream(
            Encoding.UTF8.GetBytes("[{\"Bar\":\"Bar\",\"Baaz\":2}]"));

        var list = (List<Foo>)serializer.ReadObject(ms);

        Console.WriteLine(list.Count);
    }
}

To solve the problem of having it in runtime, use below:

Type.GetType("System.Collections.Generic.List`1[[TestDll.TestType, TestDll]]")

Upvotes: 2

Related Questions