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

前端 未结 3 1093
滥情空心
滥情空心 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:16
    var jsonSerializerSettings = new JsonSerializerSettings() { 
        TypeNameHandling = TypeNameHandling.All
    };
    var json = JsonConvert.SerializeObject(instance, jsonSerializerSettings);
    

    http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题