问题
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