c# - 使用 JsonConverter 的 OnDeserialized 回调

标签 c# json.net json-deserialization

我正在尝试使用来自 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/

相关文章:

c# - 如何让反序列化在需要 int 的非整数上抛出异常?

c# - 如何将json字典序列化/反序列化为数组

java - Jackson解析错误: exception org. codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段 "Results"

c# - 谷歌的 Protocol Buffer 从 C# 到 Java - 协议(protocol)消息标记的线路类型无效

c# - 为什么在 MassTransit 中强烈推荐消息契约接口(interface)?

c# - 通过接口(interface)返回具体的仓库

c# - 从操作的哈希集中删除操作的哈希集

c# - 来自 api c# 的 HttpContent ReadAsAsync map 数据

java - Jackson反序列化: Can I inject a value with an annotation on the field of the to deserializable object?

c# - 如何使用 System.Text.Json 将 ReadOnlySpan<char> 反序列化为对象