How do you modify the Json serialization of just one field using Json.net?

前端 未结 3 1708
無奈伤痛
無奈伤痛 2021-01-21 12:45

Say for example I\'m trying to convert an object with 10 fields to Json, however I need to modify the process of serializing 1 of these fields. At the moment, I\'d have to use m

3条回答
  •  盖世英雄少女心
    2021-01-21 13:14

    You can try by decorating the property you need to modify manually with JsonConverterAttribute and pass the appropriate JsonConverter type.

    For example, using OP's original example:

    public class IntegerConverter : JsonConverter
    {
      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
      {
        serializer.Serialize(writer, Convert.ToInt32(value));
      }
    
      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
      {
        throw new NotImplementedException();
      }
    
      public override bool CanConvert(Type objectType)
      {
        return objectType == typeof(string);
      }
    }
    
    class TestJson
    {
      public string Field1 { get; set; }
      public string Field2 { get; set; }
      public string Field3 { get; set; }
    
      [JsonConverter(typeof(IntegerConverter))]
      public string Field4 { get; set; }        
    }
    

    You can then serialize the object as usual using JsonConvert:

    var test = new TestJson {Field1 = "1", Field2 = "2", Field3 = "3", Field4 = "4"};
    
    var jsonString = JsonConvert.SerializeObject(test);
    

提交回复
热议问题