gpt4 book ai didi

c# - 使用 ServiceStack.Text 序列化接口(interface)类型列表

转载 作者:行者123 更新时间:2023-11-30 12:48:34 25 4
gpt4 key购买 nike

我正在寻找将 BinaryFormatter 序列化以外的东西引入我的应用程序以最终与 Redis 一起使用的方法。 ServiceStack JSON 是我想要使用的,但它可以通过接口(interface)满足我的需求吗?它可以序列化(通过插入自定义 __type 属性)

public IAsset Content;

但不是

public List<IAsset> Contents;

- 该列表在序列化数据中为空。有什么办法可以做到这一点 - 序列化接口(interface)类型列表?

该应用又大又旧,它使用的对象的形状可能不允许更改。谢谢

最佳答案

引自http://www.servicestack.net/docs/framework/release-notes

你可能不需要做太多 :)

The JSON and JSV Text serializers now support serializing and deserializing DTOs with Interface / Abstract or object types. 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).

[...]

Note: This feature is automatically added to all Abstract/Interface/Object types, i.e. you don't need to include any [KnownType] attributes to take advantage of it.

不多:

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
});

关于c# - 使用 ServiceStack.Text 序列化接口(interface)类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com