[英]CSV Serialization of inherited types
I am attempting to serialise some records into CSV using the ServiceStack.Text library. 我正在尝试使用ServiceStack.Text库将一些记录序列化为CSV。
I am using inheritance, specifically abstract classes and the properties on the child types are not being output. 我正在使用继承,特别是抽象类,并且未输出子类型的属性。 Yes I know this is a bad idea but as I have no need to deserialise the types and I'm not making a public API.
是的,我知道这是个坏主意,但是因为我不需要反序列化类型,并且我没有制作公共API。 Regardless, this scenario seems to be supported by the docs.
无论如何,文档似乎都支持这种情况。
For this example: 对于此示例:
public abstract class ResultBase
{
public int MinuteOffset { get; set; }
public double SegmentDuration { get; set; }
}
public class EventIndex : IndexBase
{
public int EventsTotal { get; set; }
public int EventsTotalThresholded { get; set; }
}
And the code to serialise: 和要序列化的代码:
var destination = new FileInfo("C:\\somefile.txt")
using (var stream = destination.CreateText())
{
JsvStringSerializer s = new JsvStringSerializer();
var o = s.SerializeToString(results);
stream.Write(o);
CsvSerializer.SerializeToWriter(results, stream);
}
The CSV serialiser outputs this (not what I want): CSV序列化程序输出此内容(不是我想要的):
MinuteOffset,SegmentDuration
0,0
But, the JSV serialiser seems to behave as expected: 但是,JSV序列化程序似乎表现出预期的效果:
[{__type:"AnalysisBase.EventIndex, AnalysisBase",EventsTotal:0,EventsTotalThresholded:0,MinuteOffset:0,SegmentDuration:0}]
Why are there differences in the fields output, is there anyway I can get the CSV serialiser to output all child properties? 为什么在字段输出中存在差异,反正我可以让CSV序列化程序输出所有子属性?
The CsvSerializer.SerializeToWriter is a generic method which is not operating on the runtime type of the object. CsvSerializer.SerializeToWriter是一种通用方法,不能对对象的运行时类型进行操作。 If you are calling for serialization through a base type of the current instance then the serializer will not now any other properties then the base one's.
如果您要通过当前实例的基本类型进行序列化,则序列化程序现在将不再具有基本属性。
public static void SerializeToWriter<T>(T value, TextWriter writer)
{
if (value == null) return;
if (typeof(T) == typeof(string))
{
writer.Write(value);
return;
}
CsvSerializer<T>.WriteObject(writer, value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.