在Json.NET中每个树节点序列化之前和之后的自定义代码

时间:2019-02-19 12:34:07

标签: c# json.net

我正在尝试使用Json.Net序列化二叉树:

class Node
{
    Node Left;
    Node Right;
    int Data;
}

我想在每次Node序列化之前和之后添加自定义代码,因此我尝试使用自定义JsonConverter

class NodeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Node);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Console.WriteLine("Before");
        serializer.serialize(writer, value); // Oops
        Console.WriteLine("After");
    }   
}

但是这不起作用,因为JsonSerializer将无休止地调用NodeConverter.WriteJson(..)方法。

这可以在Json.NET中完成吗?

编辑: 这就是我使用自定义转换器的方式:

var root = CreateTree(); 
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms))
{
    var serializer = JsonSerializer.Create();
    serializer.Converters.Add(new NodeConverter());
    serializer.serialize(writer, root);
}

1 个答案:

答案 0 :(得分:0)

为了打破循环,您可以直接在WriteJson方法中序列化属性,例如:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    Console.WriteLine("Before");
    var n = (Node)value;
    writer.WriteStartObject();
    SerializeReferencedNode(writer, serializer, "Left", n.Left);
    SerializeReferencedNode(writer, serializer, "Right", n.Right);
    writer.WritePropertyName("Value");
    writer.WriteValue(n.Data);
    writer.WriteEndObject();
    Console.WriteLine("After");
}

private static void SerializeReferencedNode(JsonWriter writer, JsonSerializer serializer, 
                                            string propName, Node node)
{
    if (node != null)
    {
        writer.WritePropertyName(propName);
        serializer.Serialize(writer, node);
    }
}

这将导致一个简单的示例,显示以下输出:

{"Left":{"Value":123},"Right":{"Value":246},"Value":0}