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

c# – (De)使用Jil序列化DynamicObject?

发布时间:2020-12-15 20:55:04 所属栏目:百科 来源:网络整理
导读:我有一个问题(de)使用不是Newtownsoft.Json的其他json库序列化DynamicObject. (Jil,Net JSON,ServiceStack.Text ……) 这是我的可扩展对象类: public class ExpandableObject : DynamicObject{ private readonly Dictionarystring,object _fields = new Dic
我有一个问题(de)使用不是Newtownsoft.Json的其他json库序列化DynamicObject.
(Jil,Net JSON,ServiceStack.Text ……)

这是我的可扩展对象类:

public class ExpandableObject : DynamicObject
{
    private readonly Dictionary<string,object> _fields = new Dictionary<string,object>(StringComparer.OrdinalIgnoreCase);
    [JsonIgnore]
    public Dictionary<string,object> Extra { get { return _fields; } }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        var membersNames = GetType().GetProperties().Where(propInfo => propInfo.CustomAttributes
            .All(ca => ca.AttributeType != typeof (JsonIgnoreAttribute)))
            .Select(propInfo => propInfo.Name);
        return Extra.Keys.Union(membersNames);
    }

    public override bool TryGetMember(GetMemberBinder binder,out object result)
    {
        return _fields.TryGetValue(binder.Name,out result);
    }

    public override bool TrySetMember(SetMemberBinder binder,object value)
    {
        _fields[binder.Name] = value;
        return true;
    }
}

其他库(如Jil)的问题是不会调用重写的方法.
使用Newtonsoft.Json它的效果很好,但性能很糟糕.

例如 – 反序列化派生类的测试:

public class Person : ExpandableObject
{
    public int Id { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var json = "{ "Id": 12,"SomeFiled" : "hello" }";
        var person = Jil.JSON.Deserialize<Person>(json);            
    }
}

没有例外..它只是忽略了“SomeFiled”字段(应该在“Extra”中)

1.有什么解决方案吗?

2.为什么Newtonsoft.Json能够执行操作而JIL不能? (或其他快速库…).我明白被覆盖的方法应该由DLR调用..我怎样才能使它工作?

谢谢.

编辑:

现在我正在使用DeserilizeDynamic而不是Deserialize(T).现在它可以工作,我的方法由DLR调用.
现在唯一的问题是DeserilizeDynamic返回’dynamic’并且没有泛型覆盖(T).并且因为Web API无法在POST操作上解析对象的类型,例如.
未来的mabye ……

解决方法

如果您查看wiki( https://github.com/kevin-montrose/Jil/wiki/Common-Pitfalls)中的Common Trafalls文档,您将看到以下内容:

If you have a class FooBase and a class Bar : FooBase and a call like
JSON.Serialize(myBar),Jil will not serialize members inherited
from FooBase by default. Note that in many cases the generic
parameter can be inferred.

To fix this,pass an Options object with ShouldIncludeInherited set to true.

(编辑:李大同)

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

    推荐文章
      热点阅读