gpt4 book ai didi

c# - 如何使 Json.NET 序列化和反序列化也实现 IDictionary 的自定义动态类型的已声明属性?

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:06 24 4
gpt4 key购买 nike

我有一个派生自 DynamicObject 的自定义类型类型。此类型具有在类型中声明的固定属性。因此,除了他们想要的任何动态属性之外,它还允许用户提供一些必需的属性。当我使用 JsonConvert.DeserializeObject<MyType>(json)方法反序列化此类型的数据,它不设置声明的属性,但可以通过动态对象上的对象索引器属性访问这些属性。这告诉我它只是将对象视为字典,不会尝试调用已声明的属性 setter ,也不会使用它们来推断属性类型信息。

有没有人遇到过这种情况?知道如何指导 JsonConvert类在反序列化对象数据时考虑声明的属性?

我尝试使用自定义 JsonConverter ,但这需要我编写复杂的 JSON 读写方法。我希望找到一种通过覆盖 JsonContractResolver 来注入(inject)属性(property)契约(Contract)信息的方法。或 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>接口(interface),因为我的 API 中的一些用例依赖于对象是字典,而不是动态的。

  • 正在添加 [JsonProperty]将所有声明的属性序列化是不切实际的,因为它的派生类型是由其他开发人员创建的,他们不需要明确关心持久性机制。

关于如何让它正常工作有什么建议吗?

最佳答案

这里有几个问题:

  1. 您需要正确覆盖 DynamicObject.GetDynamicMemberNames() this answer 中所述给 Serialize instance of a class deriving from DynamicObject class 来自 AlbertK让 Json.NET 能够序列化您的动态属性。

    (这已在您的问题的编辑版本中修复。)

  2. 声明的属性不会显示,除非您用 [JsonProperty] 明确标记它们(如 this answer C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject 中所述)但您的类型定义是只读的,无法修改。

    这里的问题似乎是 JsonSerializerInternalWriter.SerializeDynamic() 只序列化声明的属性 JsonProperty.HasMemberAttribute == true . (我不知道为什么要在那里进行此检查,在契约(Contract)解析器中设置 CanReadIgnored 似乎更有意义。)

  3. 您希望您的类(class)实现IDictionary<string, object> ,但如果你这样做,它会破坏反序列化;声明的属性不再填充,而是添加到字典中。

    这里的问题似乎是 DefaultContractResolver.CreateContract() 返回 JsonDictionaryContract而不是 JsonDynamicContract当传入类型实现 IDictionary<TKey, TValue> 时对于任何 TKeyTValue .

假设您已解决问题 #1,问题 #2 和 #3 可以通过使用 custom contract resolver 来处理例如:

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;
}
}

然后,使用合约解析器,cache它在某处用于性能:

static IContractResolver resolver = new MyContractResolver();

然后做:

var settings = new JsonSerializerSettings
{
ContractResolver = resolver,
};
string json = JsonConvert.SerializeObject(obj, settings);

fiddle 示例 here .

关于c# - 如何使 Json.NET 序列化和反序列化也实现 IDictionary<string, object> 的自定义动态类型的已声明属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55464757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com