如何反序列化json字符串到我在运行时得到的类型的对象列表? [英] How to deserialize json string to list of objects which type I get at runtime?
本文介绍了如何反序列化json字符串到我在运行时得到的类型的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想反序列化json字符串以列出在运行时得到的类型的对象。
I want to deserialize json string to list of objects which type I get at runtime.
例如:
我的json字符串为 [{ id: 1, name: test},{ id: 2, name: test2}]
,我得到的类型是 Types.type1,types.dll
,因此我需要将其反序列化为 List< ; type1>
。如果我将得到类型 Types.type2,types.dll
,则需要将其反序列化为 List< type2>
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>
我该怎么做?
推荐答案
您可以在 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]]")
这篇关于如何反序列化json字符串到我在运行时得到的类型的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文