我能够成功地将包含Employee和Manager对象混合的列表序列化为JSON。
但是,当我尝试将JSON反序列化回List时,我正在丢失子类中的所有字段数据,当我尝试转换为任何一个子类时,我得到一个空值。如何在不丢失Employee和Manager子类字段中的数据的情况下反序列化这些用户的列表?
[DataContract]
public class User {
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
[DataContract]
public class Employee : User {
[DataMember]
public string JobTitle { get; set; }
}
[DataContract]
public class Manager : User {
[DataMember]
public string Department { get; set; }
}
编辑 - 这是我的荒漠化代码:
// abridged
public void Client() {
var jsonContent = jsonResponse.Content;
var entityList = Deserialize<IEnumerable<T>>(new JsonMediaTypeFormatter(), jsonContent);
}
protected T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class {
// Write the serialized string to a memory stream.
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
// Deserialize to an object of type T
return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
}
答案 0 :(得分:1)
您可以使用DataContractJsonSerializer
将一组已知类型作为序列化器构造函数参数传递来实现。
我创建了一个简单的测试代码来演示:
var list = new List<User>() {
new User { FirstName = "user1", LastName = "user1" },
new Employee { FirstName = "employee1", LastName = "employee1", JobTitle = "employee1" },
new Manager() { FirstName = "manager1", LastName = "manager1", Department = "manager1"}
};
var serializer = new DataContractJsonSerializer(typeof(List<User>), new [] { typeof(Employee), typeof(Manager) });
string json;
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, list);
stream.Position = 0;
using(var reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
List<User> list2;
using(var stream = new MemoryStream())
{
using(var writer = new StreamWriter(stream))
{
writer.Write(json);
writer.Flush();
stream.Position = 0;
list2 = (List<User>)serializer.ReadObject(stream);
}
}