c# - (用 Jill 反序列化动态对象?

标签 c# json serialization dynamicobject jil

我在使用其他 不是 Newtownsoft.Json 的 json 库(反)序列化 DynamicObject 时遇到问题。 (吉尔、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);            
    }
}

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

1.有什么解决办法吗?

2.为什么Newtonsoft.Json可以执行操作而JIL不能? (或其他快速图书馆......)。我知道被覆盖的方法应该由 DLR 调用。我怎样才能让它工作?

谢谢。

编辑:

现在我正在使用 DeserilizeDynamic 而不是 Deserialize(T)。现在它可以工作了,我的方法由 DLR 调用。 目前唯一的问题是 DeserilizeDynamic 返回 'dynamic' 并且没有通用覆盖 (T)。并且由于该 Web API 无法解析例如 POST 操作中的对象类型。 future 可能...

最佳答案

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

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.

关于c# - (用 Jill 反序列化动态对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349466/

相关文章:

c# - 在 .NET Core 3.1 中,RequestCookieCollection 不能再用于在单元测试中创建 cookie

c# - 如何生成嵌套的 IENumerable?

jquery - 真的很简单(?)jquery/json 错误?语法错误和需要输出的建议

javascript - JSON.stringify() 与 array.join (',' )

c# - 通过套接字发送不同类型的消息

c# - 在 Windows Phone 8.1 共享合约中显示 Viber、Whatsapp

c# - 为什么 makecert 不制作*有效*证书?

python - 将一个大的 json 文件拆分成多个小文件

php - org.json.JSONException : Value <br of type java. lang.String 无法转换为 JSONObject

java - Jackson Annotation 序列化时删除属性名称的选项