gpt4 book ai didi

c# - 使用 JsonConverter 的 OnDeserialized 回调

转载 作者:行者123 更新时间:2023-12-05 03:52:20 25 4
gpt4 key购买 nike

我正在尝试使用来自 this answerJsonConverter Can I specify a path in an attribute to map a property in my class to a child property in my JSON? 来自 Brian Rogers将 JSON 中的嵌套属性映射到平面对象。

转换器运行良好,但我需要触发 OnDeserialized 回调来填充其他属性,但它没有触发。如果我不使用转换器,则会触发回调。

例子:

string json = @"{
'response': {
'code': '000',
'description': 'Response success',
},
'employee': {
'name': 'Test',
'surname': 'Testing',
'work': 'At office'
}
}";
// employee.cs

public class EmployeeStackoverflow
{
[JsonProperty("response.code")]
public string CodeResponse { get; set; }

[JsonProperty("employee.name")]
public string Name { get; set; }

[JsonProperty("employee.surname")]
public string Surname { get; set; }

[JsonProperty("employee.work")]
public string Workplace { get; set; }

[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Workplace = "At Home!!";
}
}
// employeeConverter.cs
public class EmployeeConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
object targetObj = Activator.CreateInstance(objectType);

foreach (PropertyInfo prop in objectType.GetProperties()
.Where(p => p.CanRead && p.CanWrite))
{
JsonPropertyAttribute att = prop.GetCustomAttributes(true)
.OfType<JsonPropertyAttribute>()
.FirstOrDefault();

string jsonPath = (att != null ? att.PropertyName : prop.Name);
JToken token = jo.SelectToken(jsonPath);

if (token != null && token.Type != JTokenType.Null)
{
object value = token.ToObject(prop.PropertyType, serializer);
prop.SetValue(targetObj, value, null);
}
}

return targetObj;
}

public override bool CanConvert(Type objectType)
{
// CanConvert is not called when [JsonConverter] attribute is used
return false;
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}

}

如果我在我获得的 Employee 类中添加 [JsonConverter(typeof(EmployeeConverter))]:

=== With Converter ===
Code: 000
Name: Test
Surname: Testing
Workplace: At office

如果我从我获得的 Employee 类中删除[JsonConverter(typeof(EmployeeConverter))]:

=== With Converter ===
Code:
Name:
Surname:
Workplace: At Home!!

我的目标是获得:

=== With Converter ===
Code: 000
Name: Test
Surname: Testing
Workplace: At Home!!

转换器是否遗漏了什么?

最佳答案

创建 custom JsonConverter 后对于一个类型,转换器有责任处理反序列化期间需要完成的一切——包括

  • 调用 serialization callbacks .
  • 跳过忽略的属性。
  • 为通过属性附加到类型成员的转换器调用 JsonConverter.ReadJson()
  • 设置默认值、跳过空值、解析引用等。

完整逻辑可见JsonSerializerInternalReader.PopulateObject() ,理论上您可能需要让您的 ReadJson() 方法复制此方法。 (但在实践中,您可能只会实现一小部分必要的逻辑子集。)

简化此任务的一种方法是使用 Json.NET 自己的 JsonObjectContract类型元数据,由 JsonSerializer.ContractResolver.ResolveContract(objectType) 返回.此信息包含 Json.NET 在反序列化期间使用的序列化回调列表和 JsonpropertyAttribute 属性数据。使用此信息的转换器的修改版本如下:

// Modified from this answer https://stackoverflow.com/a/33094930
// To https://stackoverflow.com/questions/33088462/can-i-specify-a-path-in-an-attribute-to-map-a-property-in-my-class-to-a-child-pr/
// By https://stackoverflow.com/users/10263/brian-rogers
// By adding handling of deserialization callbacks and some JsonProperty attributes.
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract ?? throw new JsonException(string.Format("{0} is not a JSON object", objectType));

var jo = JToken.Load(reader);
if (jo.Type == JTokenType.Null)
return null;
else if (jo.Type != JTokenType.Object)
throw new JsonSerializationException(string.Format("Unexpected token {0}", jo.Type));

var targetObj = contract.DefaultCreator();

// Handle deserialization callbacks
foreach (var callback in contract.OnDeserializingCallbacks)
callback(targetObj, serializer.Context);

foreach (var property in contract.Properties)
{
// Check that property isn't ignored, and can be deserialized.
if (property.Ignored || !property.Writable)
continue;
if (property.ShouldDeserialize != null && !property.ShouldDeserialize(targetObj))
continue;
var jsonPath = property.PropertyName;
var token = jo.SelectToken(jsonPath);
// TODO: default values, skipping nulls, PreserveReferencesHandling, ReferenceLoopHandling, ...
if (token != null && token.Type != JTokenType.Null)
{
object value;
// Call the property's converter if present, otherwise deserialize directly.
if (property.Converter != null && property.Converter.CanRead)
{
using (var subReader = token.CreateReader())
{
if (subReader.TokenType == JsonToken.None)
subReader.Read();
value = property.Converter.ReadJson(subReader, property.PropertyType, property.ValueProvider.GetValue(targetObj), serializer);
}
}
// TODO: property.ItemConverter != null
else
{
value = token.ToObject(property.PropertyType, serializer);
}
property.ValueProvider.SetValue(targetObj, value);
}
}

// Handle deserialization callbacks
foreach (var callback in contract.OnDeserializedCallbacks)
callback(targetObj, serializer.Context);

return targetObj;
}

演示 fiddle here .

关于c# - 使用 JsonConverter 的 OnDeserialized 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62259929/

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