使用JSON.NET进行序列化时,使自定义JsonConverter尊重ItemTypeNameHandling

时间:2013-01-06 14:15:25

标签: c# .net json serialization json.net

我有一个带有基类子对象列表的对象。子对象需要自定义转换器。我无法使自定义转换器尊重ItemTypeNameHandling选项。

示例代码(创建一个新的C#Console项目,添加JSON.NET NuGet包):

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace My {
    class Program {
        private static void Main () {
            Console.WriteLine(JsonConvert.SerializeObject(
                new Box { toys = { new Spintop(), new Ball() } },
                Formatting.Indented));
            Console.ReadKey();
        }
    }

    [JsonObject] class Box
    {
        [JsonProperty (
            ItemConverterType = typeof(ToyConverter),
            ItemTypeNameHandling = TypeNameHandling.Auto)]
        public List<Toy> toys = new List<Toy>();
    }
    [JsonObject] class Toy {}
    [JsonObject] class Spintop : Toy {}
    [JsonObject] class Ball : Toy {}

    class ToyConverter : JsonConverter {
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {
            serializer.Serialize(writer, value);
        }
        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
            return serializer.Deserialize(reader, objectType);
        }
        public override bool CanConvert (Type objectType) {
            return typeof(Toy).IsAssignableFrom(objectType);
        }
    }
}

产生输出:

{
  "toys": [
    {},
    {}
  ]
}

必要的输出(如果我评论ItemConverterType = typeof(ToyConverter),行,会发生这种情况):

{
  "toys": [
    {
      "$type": "My.Spintop, Serialization"
    },
    {
      "$type": "My.Ball, Serialization"
    }
  ]
}

我尝试在serializer.TypeNameHandling方法中暂时更改ToyConverter.WriteJson的值,但它会影响不相关的属性。 (当然,我的真实转换器比这更复杂。它只是基本功能的一个例子。)

问题:如何制作JsonConverter属性的ItemTypeNameHandling尊重JsonProperty属性?

1 个答案:

答案 0 :(得分:4)

深入研究了Json.Net(4.5版本11)的源代码,看起来好像你想做什么是不可能的。

将类型写入输出的关键是这种方法:

Newtonsoft.Json.Serialization.JsonSerializerInternalWriter
    .ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract,
        JsonProperty member, JsonContainerContract containerContract,
        JsonProperty containerProperty)

这里重要的是containerContractcontainerProperty参数。在序列化而不使用转换器时,会提供这些参数,ShouldWriteType可以使用它们来确定要使用的TypeNameHandling

但是,使用转换器序列化时,不会提供这两个参数。这似乎是因为ToyConverter.WriteJson会导致调用Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue,如下所示:

SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);

请注意,最后两个参数实际上是JsonContainerContract containerContractJsonProperty containerProperty,并在链中传递给ShouldWriteType方法。问题在于:因为它们是null,ShouldWriteType方法的逻辑意味着它返回false,因此不会写入类型。

修改

this的启发,您可以通过自定义转换器的WriteJson方法来解决此问题:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    writer.WriteStartObject();
    writer.WritePropertyName("$type");
    writer.WriteValue(RemoveAssemblyDetails(value.GetType().AssemblyQualifiedName.ToString()));
    writer.WriteEndObject();
}

private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
    StringBuilder builder = new StringBuilder();

    // loop through the type name and filter out qualified assembly details from nested type names
    bool writingAssemblyName = false;
    bool skippingAssemblyDetails = false;
    for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
    {
        char current = fullyQualifiedTypeName[i];
        switch (current)
        {
            case '[':
                writingAssemblyName = false;
                skippingAssemblyDetails = false;
                builder.Append(current);
                break;
            case ']':
                writingAssemblyName = false;
                skippingAssemblyDetails = false;
                builder.Append(current);
                break;
            case ',':
                if (!writingAssemblyName)
                {
                    writingAssemblyName = true;
                    builder.Append(current);
                }
                else
                {
                    skippingAssemblyDetails = true;
                }
                break;
            default:
                if (!skippingAssemblyDetails)
                    builder.Append(current);
                break;
        }
    }

    return builder.ToString();
}

请注意,{JEN.Net source直接剥离RemoveAssemblyDetails方法。

您当然需要修改WriteJson方法以输出其余字段,但希望这样做。