加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用ServiceStack.Text序列化接口类型列表

发布时间:2020-12-15 21:43:55 所属栏目:百科 来源:网络整理
导读:我正在寻找将BinaryFormatter序列化以外的东西引入我的应用程序以最终使用Redis的方法. ServiceStack JSON是我想要使用的,但它可以用接口做我需要的吗? 它可以序列化(通过插入自定义__type属性) public IAsset Content; 但不是 public ListIAsset Contents;
我正在寻找将BinaryFormatter序列化以外的东西引入我的应用程序以最终使用Redis的方法. ServiceStack JSON是我想要使用的,但它可以用接口做我需要的吗?
它可以序列化(通过插入自定义__type属性)

public IAsset Content;

但不是

public List<IAsset> Contents;

– 列表在序列化数据中显示为空.有没有办法做到这一点 – 序列化接口类型列表?

该应用程序是大而老的,它使用的对象的形状可能不会被允许改变.
谢谢

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读