JsonSerializer not serializing derived class properties

陌路散爱 提交于 2019-12-24 06:46:01

问题


I have a class like below which is added to the project/solution as reference

public class FileContents
{
    public List<RecordBase> Records { get; set; }
}

public class RecordBase
{
    public int LineNumber { get; set; }
}

There few other class which are not added to the reference but dynamicaly loaded and those classes are derived from RecordBase class the below is the snippet on how it is loaded

var fileContents = new FileContents();
var dll = Assembly.LoadFile(derivedClassesAssemblyLocation);
Type type = dll.GetExportedTypes().Where(a =>  
                           a.Name.Equals(className)).FirstOrDefault();
if (type != null && type.Name == className)
{
    dynamic instance = Activator.CreateInstance(type);

    //All properties are populated to the instance
    //.....
    //.....

    fileContents.Records.Add(instance)
}

The below is the other class mentioned earlier which are derived from the RecordBase

public class RecordStyleA : RecordBase
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }
}

Loading and serializing

 var result = new FileContents();
 //Logic to load ....

 var serializer = new ServiceStack.Text.JsonStringSerializer();
 var json = serializer.SerializeToString(result);

Here when I try to serilaize the FileContents object it is skipping properties available in the derived class (for example from RecordStyleA)

Here Derived (RecordStyleA) class is conditionally loaded and its property might also vary depending on the condion. The drived classes are created on the fly.

Please help me in solving this issue


回答1:


Firstly inheritance in DTO's should be avoided, if you must use it then you should make your base class abstract so the ServiceStack Serializer knows when to emit the dynamic type information.

Note the 2 most common API's for serializing to JSON is to use the static JsonSerializer class, e.g:

var json = JsonSerializer.SerializeToString(result);

Or the .ToJson()/.FromJson() extension methods, e.g:

var json = result.ToJson();


来源:https://stackoverflow.com/questions/31184938/jsonserializer-not-serializing-derived-class-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!