gpt4 book ai didi

c# - Json.NET:反序列化嵌套字典

转载 作者:IT老高 更新时间:2023-10-28 12:50:09 28 4
gpt4 key购买 nike

将对象反序列化为 Dictionary 时( JsonConvert.DeserializeObject<IDictionary<string,object>>(json) ) 嵌套对象被反序列化为 JObject s。是否可以强制将嵌套对象反序列化为 Dictionary s?

最佳答案

我找到了将所有嵌套对象转换为 Dictionary<string,object> 的方法通过提供 CustomCreationConverter实现:

class MyConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}

public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject
|| reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);

// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}

class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText(@"c:\test.json");
var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(
json, new JsonConverter[] {new MyConverter()});
}
}

文档: CustomCreationConverter with Json.NET

关于c# - Json.NET:反序列化嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416017/

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