与低级类型不同地序列化根级别类型

时间:2014-01-29 15:20:49

标签: c# serialization json.net

在Json.NET中,序列化层次结构中的根级别类型是否可能与层次结构中较低级别遇到的引用不同?

例如,使用此类型

class Serialized {
  public Serialized Serialized;
  public int A;
}

在此设置中

var serialized = new Serialized() { A = 1 };
var serialized2 = new Serialized() { A = 2 };
serialized.Serialized = serialized2;

string json = GetJson(serialized);

其中json是

{
  "A":1
  "Serialized": {
    "ref":2
  }
}

具体来说,根级序列化应该使用默认的序列化策略,而较低级别的序列化应该使用自定义转换器(或类似的)。

1 个答案:

答案 0 :(得分:0)

您需要定义自定义JsonConverter并使用它装饰Serialized属性:

public class PropertyConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    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)
    {
        if (value == null) return;

        var serialized = (Serialized)value;

        writer.WriteStartObject();
        writer.WritePropertyName("ref");
        writer.WriteValue(serialized.A);
        writer.WriteEndObject();
    }
}

你的班级:

class Serialized {
    [JsonConverter(typeof(PropertyConverter))
    public Serialized Serialized;
    public int A;
}

这仅适用于一个嵌套级别。如果需要它可以使用多个嵌套级别,则需要修改转换器:

public class PropertyConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    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)
    {
        if (value == null) return;

        var serialized = (Serialized)value;

        writer.WriteStartObject();
        writer.WritePropertyName("ref");
        writer.WriteValue(serialized.A);
        if(serialized.Serialized != null)
        {
            writer.WritePropertyName("nested");
            writer.WriteValue(JsonConvert.SerializeObject(serialized.Serialized, new JsonConverter[] {new PropertyConverter()}));
        }
        writer.WriteEndObject();
    }
}