JSON serializer adding extra character as '\'in response while serializing custom datatype in custom JsonConverter

对着背影说爱祢 提交于 2019-12-11 12:03:19

问题


I am using custom JsonConverter(CustomInfoConverter ) to do some manipulation in each of my custom dot net type(CustomType) which is getting parse.

Below is the code for custom 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();
    }


}

The issue I am facing here is extra character'\' is getting appended here, So my response looks like JsonConvert.SerializeObject(customType) is serializing customType object and again default serializer is serializing it(correct me if I am wrong). What would be solution for this?

   {
  "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}",
    }
  ],

}

From here I came to know that it may be because of re-json-ing, So, what would be the solution for this?


回答1:


The problem is this line:

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

Instead you should be doing this to avoid the double-serialization:

serializer.Serialize(writer, customType);

However, since you are trying to serialize the same object that your converter converts, the above will result in an self-referencing loop. In this case you need to use a new instance of the serializer. Try this instead:

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

Note: if you are using any other converters (or custom settings), the new serializer instance will not know about them unless you specifically copy them from the outer serializer. If you need to do this, make sure you do not copy the CustomInfoConverter to the new instance or you will end up with the self-referencing loop problem again. To copy the converters, replace the above with the following:

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


来源:https://stackoverflow.com/questions/33524379/json-serializer-adding-extra-character-as-in-response-while-serializing-custo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!