【发布时间】:2011-05-24 19:03:57
【问题描述】:
我正在使用DataContractJsonSerializer 反序列化来自外部服务的对象。在大多数情况下,这对我来说效果很好。但是,在一种情况下,我需要反序列化 JSON,其中包含一个对象列表,这些对象都继承自同一个基类,但该列表中有许多不同类型的对象。
我知道可以通过在序列化程序的构造函数中包含已知类型的列表来轻松完成此操作,但我无法访问生成此 JSON 服务的代码。我使用的类型与服务中使用的类型不同(主要是类名和命名空间不同)。换句话说,序列化数据的类与我将用来反序列化它的类不同,即使它们非常相似。
使用 XML DataContractSerializer,我可以传入 DataContractResolver 以将服务类型映射到我自己的类型,但 DataContractJsonSerializer 没有这样的构造函数。 有没有办法做到这一点? 我能找到的唯一选择是:编写我自己的反序列化器,或使用未经测试且“不应在生产环境。”
这是一个例子:
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class Student : Person
{
[DataMember]
public int StudentId { get; set; }
}
class Program
{
static void Main(string[] args)
{
var jsonStr = "[{\"__type\":\"Student:#UnknownProject\",\"Name\":\"John Smith\",\"StudentId\":1},{\"Name\":\"James Adams\"}]";
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(jsonStr);
writer.Flush();
stream.Position = 0;
var s = new DataContractJsonSerializer(typeof(List<Person>), new Type[] { typeof(Student), typeof(Person) });
// Crashes on this line with the error below
var personList = (List<Person>)s.ReadObject(stream);
}
}
}
这是上面评论中提到的错误:
Element ':item' contains data from a type that maps to the name
'http://schemas.datacontract.org/2004/07/UnknownProject:Student'. The
deserializer has no knowledge of any type that maps to this name. Consider using
a DataContractResolver or add the type corresponding to 'Student' to the list of
known types - for example, by using the KnownTypeAttribute attribute or by adding
it to the list of known types passed to DataContractSerializer.
【问题讨论】:
标签: c# .net json .net-4.0 deserialization