Deserialize json with auto-trimming strings

后端 未结 3 1927
我寻月下人不归
我寻月下人不归 2020-12-20 12:20

I use Newtonsoft.Json library

Is there a way to trim spaces from any string data during deserialization?

class Program
{
    class Person
    {
              


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 12:57

    You could write your own JsonConverter:

    public class TrimmingConverter : JsonConverter
    {
        public override bool CanRead => true;
        public override bool CanWrite => false;
    
        public override bool CanConvert(Type objectType) => objectType == typeof(string);
    
        public override object ReadJson(JsonReader reader, Type objectType,
                                        object existingValue, JsonSerializer serializer)
        {
            return ((string)reader.Value)?.Trim();
        }
    
        public override void WriteJson(JsonWriter writer, object value, 
                                       JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    You can use it like this to apply to all string fields:

    var json = @"{ name:"" John "" }"
    var p = JsonConvert.DeserializeObject(json, new TrimmingConverter());
    Console.WriteLine("Name is: \"{0}\"", p.Name);
    //Name is: "John"
    

    Or you can apply this to certain fields only:

    public class Person
    {
        [JsonProperty("name")]
        [JsonConverter(typeof(TrimmingConverter))] // <-- that's the important line
        public string Name { get; set; }
        [JsonProperty("other")]
        public string Other { get; set; }
    }
    
    var json = @"{ name:"" John "", other:"" blah blah blah "" }"
    var p = JsonConvert.DeserializeObject(json);
    Console.WriteLine("Name is: \"{0}\"", p.Name);
    Console.WriteLine("Other is: \"{0}\"", p.Other);
    
    //Name is: "John"
    //Other is: " blah blah blah "
    

提交回复
热议问题