我有一个自DynamicObject
类型派生的自定义类型。此类型具有在该类型中声明的固定属性。因此,它允许用户除了提供所需的任何动态属性外,还提供一些必需的属性。当我使用JsonConvert.DeserializeObject<MyType>(json)
方法反序列化此类型的数据时,它不会设置声明的属性,但是可以通过动态对象上的对象索引器属性来访问这些属性。这告诉我,它只是将对象视为字典,并且不会尝试调用已声明的属性设置器,也不会使用它们来推断属性类型信息。
以前有人遇到过这种情况吗?知道如何在反序列化对象数据时指示JsonConvert
类考虑声明的属性吗?
我尝试使用自定义JsonConverter
,但这需要我编写复杂的JSON读取和写入方法。我希望找到一种通过覆盖JsonContractResolver
或JsonConverter
等来注入财产合同信息的方法。
//#define IMPLEMENT_IDICTIONARY
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
public class MyDynamicObject : DynamicObject
#if IMPLEMENT_IDICTIONARY
, IDictionary<string, object>
#endif
{
private Dictionary<string, object> m_Members;
public MyDynamicObject()
{
this.m_Members = new Dictionary<string, object>();
}
#if IMPLEMENT_IDICTIONARY
public int Count { get { return this.m_Members.Count; } }
public ICollection<string> Keys => this.m_Members.Keys;
public ICollection<object> Values => this.m_Members.Values;
bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false;
/// <summary>
/// Gets or sets the specified member value.
/// </summary>
/// <param name="memberName">Name of the member in question.</param>
/// <returns>A value for the specified member.</returns>
public object this[string memberName]
{
get
{
object value;
if (this.m_Members.TryGetValue(memberName, out value))
return value;
else
return null;
}
set => this.m_Members[memberName] = value;
}
#endif
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
this.m_Members.TryGetValue(binder.Name, out result);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this.m_Members[binder.Name] = value;
return true;
}
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
return this.m_Members.Remove(binder.Name);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
var names = base.GetDynamicMemberNames();
return this.m_Members.Keys;
}
#if IMPLEMENT_IDICTIONARY
bool IDictionary<string, object>.ContainsKey(string memberName)
{
return this.m_Members.ContainsKey(memberName);
}
public void Add(string memberName, object value)
{
this.m_Members.Add(memberName, value);
}
public bool Remove(string memberName)
{
return this.m_Members.Remove(memberName);
}
public bool TryGetValue(string memberName, out object value)
{
return this.m_Members.TryGetValue(memberName, out value);
}
public void Clear()
{
this.m_Members.Clear();
}
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> member)
{
((IDictionary<string, object>)this.m_Members).Add(member);
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> member)
{
return ((IDictionary<string, object>)this.m_Members).Contains(member);
}
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
((IDictionary<string, object>)this.m_Members).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> member)
{
return ((IDictionary<string, object>)this.m_Members).Remove(member);
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return this.m_Members.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.m_Members.GetEnumerator();
}
#endif
}
public class ProxyInfo
{
public string Server;
public int Port;
}
public class CustomDynamicObject : MyDynamicObject
{
//[JsonProperty] // NOTE: Cannot do this.
public string Name { get; set; }
//[JsonProperty] // NOTE: Cannot do this.
public ProxyInfo Proxy { get; set; }
}
static void Main(string[] args)
{
dynamic obj = new CustomDynamicObject()
{
Name = "Test1",
Proxy = new ProxyInfo() { Server = "http://test.com/", Port = 10102 }
};
obj.Prop1 = "P1";
obj.Prop2 = 320;
string json = JsonConvert.SerializeObject(obj); // Returns: { "Prop1":"P1", "Prop2":320 }
// ISSUE #1: It did not serialize the declared properties. Only the dynamically added properties are serialized.
// Following JSON was expected. It produces correct JSON if I mark the declared properties with
// JsonProperty attribute, which I cannot do in all cases.
string expectedJson = "{ \"Prop1\":\"P1\", \"Prop2\":320, \"Name\":\"Test1\", \"Proxy\":{ \"Server\":\"http://test.com/\", \"Port\":10102 } }";
CustomDynamicObject deserializedObj = JsonConvert.DeserializeObject<CustomDynamicObject>(expectedJson);
// ISSUE #2: Deserialization worked in this case, but does not work once I re-introduce the IDictionary interface on my base class.
// In that case, it does not populate the declared properties, but simply added all 4 properties to the underlying dictionary.
// Neither does it infer the ProxyInfo type when deserializing the Proxy property value and simply bound the JObject token to
// the dynamic object.
}
}
}
我希望它像常规类型一样使用反射来解析属性及其类型信息。但这似乎只是将对象视为常规词典。
请注意:
我无法删除IDictionary<string, object>
接口,因为我API中的某些用例依赖于该对象作为字典,而不是动态的。
在要声明的所有要序列化的属性中添加[JsonProperty]
是不切实际的,因为它的派生类型是由其他开发人员创建的,并且它们不需要显式关心持久性机制。
关于如何使其正常工作的任何建议?
答案 0 :(得分:0)
我不知道ProxyInfo类的内容是什么。但是,同时使用字符串作为Name和Proxy属性时,反序列化可以正常工作。请检查以下工作示例:
class Program
{
static void Main(string[] args)
{
// NOTE: This is how I load the JSON data into the new type.
var obj = JsonConvert.DeserializeObject<MyCustomDynamicObject>("{name:'name1', proxy:'string'}");
var proxy = obj.Proxy;
var name = obj.Name;
}
}
public class MyDynamicObject : DynamicObject
{
// Implements the functionality to store dynamic properties in
// dictionary.
// NOTE: This base class does not have any declared properties.
}
// NOTE: This is the actual concrete type that has declared properties
public class MyCustomDynamicObject : MyDynamicObject
{
public string Name { get; set; }
public string Proxy { get; set; }
}
答案 1 :(得分:0)
您在这里遇到一些问题:
您需要按照DynamicObject.GetDynamicMemberNames()
正确覆盖this answer到{em> Serialize instance of a class deriving from DynamicObject class 的AlbertK
才能使Json.NET能够覆盖序列化您的动态属性。
(此问题已在您的问题的编辑版本中得到解决。)
已声明的属性不会显示,除非您用[JsonProperty]
显式标记它们(如this answer到 C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject 所述),但是您的类型定义是是只读的,无法修改。
这里的问题似乎是JsonSerializerInternalWriter.SerializeDynamic()
仅序列化JsonProperty.HasMemberAttribute == true
的声明属性。 (我不知道为什么要在此进行检查,在合同解析器中设置CanRead
或Ignored
似乎更有意义。)
您希望您的类实现IDictionary<string, object>
,但是如果这样做,则会破坏反序列化;声明的属性不再填充,而是添加到字典中。
这里的问题似乎是,当传入类型为JsonDictionaryContract
和{{1}中的任何一个实现JsonDynamicContract
时,DefaultContractResolver.CreateContract()
返回IDictionary<TKey, TValue>
而不是TKey
}。
假设您已解决问题#1,则可以使用custom contract resolver处理问题#2和#3,如下所示:
TValue
然后,要使用合同解析器,cache将其用于提高性能:
public class MyContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
// Prefer JsonDynamicContract for MyDynamicObject
if (typeof(MyDynamicObject).IsAssignableFrom(objectType))
{
return CreateDynamicContract(objectType);
}
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
// If object type is a subclass of MyDynamicObject and the property is declared
// in a subclass of MyDynamicObject, assume it is marked with JsonProperty
// (unless it is explicitly ignored). By checking IsSubclassOf we ensure that
// "bookkeeping" properties like Count, Keys and Values are not serialized.
if (type.IsSubclassOf(typeof(MyDynamicObject)) && memberSerialization == MemberSerialization.OptOut)
{
foreach (var property in properties)
{
if (!property.Ignored && property.DeclaringType.IsSubclassOf(typeof(MyDynamicObject)))
{
property.HasMemberAttribute = true;
}
}
}
return properties;
}
}
然后执行:
static IContractResolver resolver = new MyContractResolver();
提琴here。