How to serialize object to json with type info using Newtonsoft.Json?

前端 未结 3 1101
滥情空心
滥情空心 2020-12-15 16:53

I want to have a property with type name in JSON when I serialize objects of certain types. I wrote a converter:

public class TypeInfoConverter : JsonConvert         


        
3条回答
  •  无人及你
    2020-12-15 17:29

    Have you tried creating a new instance of JsonSerializer, then copying all the converters from the original serializer except the converter that causes the infinite recursion?

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            Converters = serializer.Converters.Where(s => !(s is TypeInfoConverter)).ToList()
            // also copy any other custom settings from the serializer you wish to pass through
            DateFormatHandling = serializer.DateFormatHandling,
            MissingMemberHandling = serializer.MissingMemberHandling,
            NullValueHandling = serializer.NullValueHandling,
            Formatting = serializer.Formatting
        };
        var localSerializer = JsonSerializer.Create(settings);
    
        var jObject = JObject.FromObject(value, localSerializer);
        jObject.AddFirst(new JProperty("Type", value.GetType().Name));
        jObject.WriteTo(writer);
    }
    

提交回复
热议问题