C# JSON custom serialization

前端 未结 1 688
离开以前
离开以前 2020-12-03 07:06

Is there a way/library that will allow me to customize JSON serialization similar to GSON custom serializers?

Here is what I\'m trying to get:

this object: <

1条回答
  •  眼角桃花
    2020-12-03 07:51

    First i suggest to use newton json dll.

    Second your need create custom JsonConverter for KeyValuePair like this:

      public class PairConverter : JsonConverter
      {
        public override bool CanConvert(Type objectType)
        {
           return objectType == typeof(KeyValuePair);
        }
    
        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)
        {
          var item = (KeyValuePair)value;
          writer.WriteValue(item.Value);
          writer.Flush();
        }
      }
    

    And than add JsonConverter attribute for 'Age' property like this:

     public class Persons
     {
       [JsonConverter(typeof(PairConverter))]
       public KeyValuePair Age { get; set; }
     }
    

    Finally, example of usage:

     var persons = new Persons()
     {
        Age = new KeyValuePair("Age", 10)
     };
     var json = JsonConvert.SerializeObject(persons); // {Age:10}
    

    0 讨论(0)
提交回复
热议问题