(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 ……
解决方法
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。