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

前端 未结 3 1711
無奈伤痛
無奈伤痛 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 12:50

    If you have access to the class (and you always need it to be serialized the same way) you could modify the class to your needs. Suppose this.is the class:

    public class MyClass
    {
        public string Value4 {get; set;}
    }
    

    If you want value 4 to be serialized as an int you could do this:

    public class MyClass
    {
        [JsonIgnore()]
        public string Value4 {get; set;}
    
        public int Value4AsInt
        {
            return Convert.ToInt32(Value4);
        }
    }
    

提交回复
热议问题