问题
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