[英]Serialize list of interface types with ServiceStack.Text
I'm looking at ways to introduce something other than BinaryFormatter serialization into my app to eventually work with Redis. 我正在寻找将BinaryFormatter序列化以外的东西引入我的应用程序以最终使用Redis的方法。 ServiceStack JSON is what I would like to use, but can it do what I need with interfaces?
ServiceStack JSON是我想要使用的,但它可以用接口做我需要的吗? It can serialize (by inserting custom __type attribute)
它可以序列化(通过插入自定义__type属性)
public IAsset Content;
but not 但不是
public List<IAsset> Contents;
- the list comes up empty in serialized data. - 列表在序列化数据中显示为空。 Is there any way to do this - serialize a list of interface types?
有没有办法做到这一点 - 序列化接口类型列表?
The app is big and old and the shape of objects it uses is probably not going to be allowed to change. 该应用程序是大而老的,它使用的对象的形状可能不会被允许改变。 Thanks
谢谢
Quoting from http://www.servicestack.net/docs/framework/release-notes 引自http://www.servicestack.net/docs/framework/release-notes
You probably don't have to do much :) 你可能不需要做太多:)
The JSON and JSV Text serializers now support serializing and deserializing DTOs with Interface / Abstract or object types.
JSON和JSV Text序列化程序现在支持使用Interface / Abstract或对象类型对DTO进行序列化和反序列化。 Amongst other things, this allows you to have an IInterface property which when serialized will include its concrete type information in a __type property field (similar to other JSON serializers) which when serialized populates an instance of that concrete type (provided it exists).
除此之外,这允许您拥有一个IInterface属性,在序列化时,它将在__type属性字段中包含其具体类型信息(类似于其他JSON序列化程序),序列化时会填充该具体类型的实例(如果存在)。
[...]
[...]
Note: This feature is automatically added to all Abstract/Interface/Object types, ie you don't need to include any [KnownType] attributes to take advantage of it.
注意:此功能会自动添加到所有抽象/接口/对象类型,即您不需要包含任何[KnownType]属性来利用它。
By not much: 不多:
public interface IAsset
{
string Bling { get; set; }
}
public class AAsset : IAsset
{
public string Bling { get; set; }
public override string ToString()
{
return "A" + Bling;
}
}
public class BAsset : IAsset
{
public string Bling { get; set; }
public override string ToString()
{
return "B" + Bling;
}
}
public class AssetBag
{
[JsonProperty(TypeNameHandling = TypeNameHandling.None)]
public List<IAsset> Assets { get; set; }
}
class Program
{
static void Main(string[] args)
{
try
{
var bag = new AssetBag
{
Assets = new List<IAsset> {new AAsset {Bling = "Oho"}, new BAsset() {Bling = "Aha"}}
};
string json = JsonConvert.SerializeObject(bag, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto
});
var anotherBag = JsonConvert.DeserializeObject<AssetBag>(json, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.