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

孤街浪徒 提交于 2019-12-11 11:46:41

问题


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?


回答1:


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]]")


来源:https://stackoverflow.com/questions/7953214/how-to-deserialize-json-string-to-list-of-objects-which-type-i-get-at-runtime

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