JSON.net (de)serialize untyped property

后端 未结 2 1690
慢半拍i
慢半拍i 2020-12-07 03:30

Suppose I have a class like this:

public class Example {
    public int TypedProperty { get; set; }
    public object UntypedProperty { get; set; }
}
         


        
2条回答
  •  眼角桃花
    2020-12-07 03:55

    Lookup SerializeWithJsonConverters.htm and ReadingWritingJSON. Call: JsonConvert.SerializeObject(example, new ObjectConverter());

    class ObjectConverter : JsonConverter
    {
    public override bool CanConvert(Type objectType)
    {
      return objectType == typeof(Example);
    }
    
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      throw new NotImplementedException();
    }
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      Example e = (Example)value;
    
      writer.WriteStartObject();
    
      writer.WritePropertyName("TypedProperty");
      writer.WriteValue(e.TypedProperty);
    
      writer.WritePropertyName("UntypedProperty");
      writer.WriteStartObject();
    
      writer.WritePropertyName("$type");
      writer.WriteValue(e.UntypedProperty.GetType().FullName);
    
      writer.WritePropertyName("$value");
      writer.WriteValue(e.UntypedProperty.ToString());
    
      writer.WriteEndObject();
    
      writer.WriteEndObject();
    }
    }
    

提交回复
热议问题