自定义转换器覆盖ContractResolver

时间:2013-11-19 05:19:52

标签: c# json.net

我正在尝试使用自定义转换器修改对象类型,如here所述,以及CamelCasePropertyNamesContractResolver

所以转换器是这样的(这里什么都不做):

class MyJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsSubclassOf(typeof(MyType));
    }

    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)
    {
        JToken t = JToken.FromObject(value);
        t.WriteTo(writer);
    }
}

我这样使用它:

var jsonSerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
jsonSerializationSettings.Converters.Add(new MyJsonConverter());
var camelCaseJsonOutput = await JsonConvert.SerializeObjectAsync(myObject, Formatting.None, jsonSerializationSettings);

但是序列化输出显示以大写字母开头的属性,因此似乎使用我的转换器以某种方式取消了驼峰式合约解析器......

1 个答案:

答案 0 :(得分:2)

创建时

JToken t = JToken.FromObject(value);

它创建原始json而不进行格式化。 所以,你可以用你自己的方式控制它,骆驼,帕斯卡,wHaTeVeR。

例如:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var myType = value as MyType;
    if (myType != null)
    {
        writer.WriteStartObject();
        writer.WritePropertyName("myProperty");
        serializer.Serialize(writer, myType.myProperty); // Using this will allow to serialize inner values with CamelCasePropertyNamesContractResolver
        writer.WritePropertyName("Inner");
        serializer.Serialize(writer, myType.Inner);
      ...
        writer.WriteEndObject();
    }
}

用于使用camelCase和其他属性进行序列化对象我将采用这种方式(可能效率不高)

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        writer.WritePropertyName("_custom_Prop_");
        writer.WriteValue("Custom Property value");

        WriteObjectProperties(writer, value);

        writer.WriteEndObject();
    }

    private static void WriteObjectProperties(JsonWriter writer, object value)
    {
        var myJsonWriter = new JTokenWriter();
        var js = new JsonSerializer();
        js.ContractResolver = new CamelCasePropertyNamesContractResolver();
        js.Serialize(myJsonWriter, value);
        var childTokens = myJsonWriter.Token.Children();
        foreach (var childToken in childTokens)
        {
            childToken.WriteTo(writer);
        }
    }