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

前端 未结 3 1096
滥情空心
滥情空心 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:30

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        var converters = serializer.Converters.Where(x => !(x is TypeInfoConverter)).ToArray();
    
        var jObject = JObject.FromObject(value);
        jObject.AddFirst(new JProperty("Type", value.GetType().Name));
        jObject.WriteTo(writer, converters);
    }
    

提交回复
热议问题