更新时间:2023-02-15 18:26:03
我目前正在处理的项目有一个非常相似的问题:我想制作一个自定义JsonConverter
并通过属性将其映射到我的实体,但随后代码陷入了无限循环.
I had a very similar problem with a project that I am currently working on: I wanted to make a custom JsonConverter
and map it to my entities via attributes, but then the code got trapped in an infinite loop.
在我的情况下,技巧是使用serializer.Populate
而不是JObject.ToObject
(即使我愿意也不能使用.ToObject
;我使用的是3.5.8版,其中该功能不存在).下面是我的ReadJson
方法作为示例:
What did the trick in my case was using serializer.Populate
instead of JObject.ToObject
(I couldn't use .ToObject
even if I wanted to; I am using version 3.5.8, in which this function does not exist). Below is my ReadJson
method as an example:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JContainer lJContainer = default(JContainer);
if (reader.TokenType == JsonToken.StartObject)
{
lJContainer = JObject.Load(reader);
existingValue = Convert.ChangeType(existingValue, objectType);
existingValue = Activator.CreateInstance(objectType);
serializer.Populate(lJContainer.CreateReader(), existingValue);
}
return existingValue;
}