gpt4 book ai didi

c# - JSON.NET 将实现 IDictionary 的对象反序列化为字典,如何强制常规类序列化?

转载 作者:行者123 更新时间:2023-11-30 20:33:03 25 4
gpt4 key购买 nike

假设我定义了一个 interface :

public interface IExtensibleObject : IDictionary<string, object>
{
// Some members here, but it doesn't matter for this question
}

我设计了一个实现整个接口(interface)的类:

public class Customer : IExtensibleObject
{
public Guid Id { get; set; }

// IExtensibleObject implemented members
}

当我尝试反序列化 JSON string 时至Customer ,JSON.NET将访问IDictionary<TKey, TValue>索引器设置Id属性(即 instance["Id"] = value ):

Customer customer = JsonConvert.DeserializeObject<Customer>(@"{""Id"":""bcf66a92-00ea-4124-afa7-a6c200ae5886""}");

是否有某种内置方法可以避免整个行为?。我需要将整个对象反序列化为常规对象,即使它实现 IDictionary<TKey, TValue> .

最佳答案

您可以使用自定义契约(Contract)解析器来完成此操作。默认合约解析器检查类是否实现了 IDictionary,如果是,则对其进行序列化\反序列化。您可以更改它:

class CustomResolver : DefaultContractResolver {
protected override JsonContract CreateContract(Type objectType) {
// if type implements your interface - serialize it as object
if (typeof(IExtensibleObject).IsAssignableFrom(objectType)) {
return base.CreateObjectContract(objectType);
}

return base.CreateContract(objectType);
}
}

然后就是:

 var settings = new JsonSerializerSettings(); // or change default settings
settings.ContractResolver = new CustomResolver();
Customer customer = JsonConvert.DeserializeObject<Customer>(@"{""Id"":""bcf66a92-00ea-4124-afa7-a6c200ae5886""}", settings);

关于c# - JSON.NET 将实现 IDictionary<TKey, TValue> 的对象反序列化为字典,如何强制常规类序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40675841/

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