public interface Base { }
public class BaseA : Base { public string Name { set; get; } }
public class BaseB : Base { public int Age { set; get; } }
public class Root { public Base Base { set; get; } }
void Test()
{
var setting = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto };
var root = new Root() { Base = new BaseA { Name = "Name" } };
Console.WriteLine(JsonConvert.SerializeObject(root, setting));
Console.WriteLine( JsonConvert.SerializeObject(root));
}
{"Base":{"$type":"Server.Controllers.SetMsgTempController+BaseA, Server","Name":"Name"}}
{"Base":{"Name":"Name"}}
如果加上var setting = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto };
那么序列化出来的会带有类的信息,这样在反序列化的时候就可以根据信息反序列化回去。
所以在反序列化的时候同样也要加上这个设置。
var setting = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto };
var root = new Root() { Base = new BaseA { Name = "Name" } };
var content = JsonConvert.SerializeObject(root, setting);
JsonConvert.DeserializeObject<Root>(content, setting);