【问题标题】:(De)Serialize DynamicObject with Jil?(用 Jill 反序列化动态对象?
【发布时间】:2023-04-10 20:19:01
【问题描述】:

我在使用其他 Newtownsoft.Json 的 json 库(反)序列化 DynamicObject 时遇到问题。 (Jil、NetJSON、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 返回“动态”并且没有通用覆盖 (T)。并且由于该 Web API 无法解析 POST 操作上的对象类型,例如。 也许将来……

【问题讨论】:

    标签: c# json serialization dynamicobject jil


    【解决方案1】:

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

    如果你有一个类 FooBase 和一个类 Bar : FooBase 和一个类似的调用 JSON.Serialize(myBar), Jil 不会序列化继承的成员 默认来自 FooBase。请注意,在许多情况下,通用 参数可以推断出来。

    要解决此问题,请传递一个将 ShouldIncludeInherited 设置为的 Options 对象 真的。

    【讨论】:

    • 嗨,利亚姆,感谢您的回答,但这并不能解决问题。我的代码中有一个错误。现在 DLR 使用 Jil 的 DeserializeDynmic 工作并调用方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多