JSON序列化程序在自定义JsonConverter

时间:2015-11-04 14:26:58

标签: c# json serialization json.net

我正在使用自定义JsonConverter(CustomInfoConverter)在我的每个自定义点网类型(CustomType)中进行一些操作以进行解析。

以下是自定义JsonConverter的代码:

public class CustomInfoConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(CustomType);
    }
    public override bool CanRead
    {
        get
        {
            return false;
        }
    }
    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var customType = (CustomType)value;
        if (customType == null || null== customType.TimeZone) return;
        //DateTime currentDateTime = customType.Date??DateTime.Now;
        DateTime currentDateTime = DateTime.SpecifyKind(customType.Date ?? DateTime.Now, DateTimeKind.Unspecified);

        DateTime userDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentDateTime, customType.TimeZone);
        customType.Date = userDateTime;
        writer.WriteValue(JsonConvert.SerializeObject(customType) );


    }

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


}

我在这里遇到的问题是额外的字符'\'被附加在这里,所以我的响应看起来像JsonConvert.SerializeObject(customType)序列化customType对象,并且默认序列化器再次序列化它(如果我错了,请纠正我)。对此有什么解决方法?

   {
  "Data": [
    {
      "Type": "someThing",
      "Created": "{\"Date\":\"2015-11-05T01:09:21.6721171+05:30\",\"User\":{\"Upn\":\"james\",\"FirstName\":\"James\",\"LastName\":\"Johnson\",\"Id\":\"69cb471e-da83-48c3-8f60-d1bb29d41177\",\"Name\":\"Johnson\"},\"TimeZone\":{\"Id\":\"India Standard Time\",\"DisplayName\":\"(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi\",\"StandardName\":\"India Standard Time\",\"DaylightName\":\"India Daylight Time\",\"BaseUtcOffset\":\"05:30:00\",\"AdjustmentRules\":null,\"SupportsDaylightSavingTime\":false},\"Latitude\":null,\"Longitude\":null}",
    }
  ],

}

here我开始知道这可能是因为重新开始, 那么,解决方案是什么呢?

1 个答案:

答案 0 :(得分:3)

问题在于这一行:

writer.WriteValue(JsonConvert.SerializeObject(customType));

相反,你应该这样做以避免双序列化:

serializer.Serialize(writer, customType);

但是,由于您尝试序列化转换器转换的同一对象,因此上面将导致自引用循环。在这种情况下,您需要使用序列化程序的新实例。试试这个:

new JsonSerializer().Serialize(writer, customType);

注意:如果您使用任何其他转换器(或自定义设置),新的序列化程序实例将不会知道它们,除非您从外部序列化程序专门复制它们。如果您需要这样做,请确保CustomInfoConverter复制到新实例,否则您将再次遇到自引用循环问题。要复制转换器,请使用以下内容替换以上内容:

JsonSerializer innerSerializer = new JsonSerializer();
foreach (var converter in serializer.Converters.Where(c => !(c is CustomInfoConverter)))
{
    innerSerializer.Converters.Add(converter);
}
innerSerializer.Serialize(writer, customType);