running a transformation on a Json DeserializeObject for a property

后端 未结 2 2082
后悔当初
后悔当初 2020-12-07 04:47

Assuming a json string like the following:

string json = \'{\"string_property\":\"foo_bar\", ... other objects here ...}\';

I was wondering

2条回答
  •  感动是毒
    2020-12-07 05:26

    You can transform your string properties as you deserialize your root object by using a custom JsonConverter targeted at all string type values:

    public class ReplacingStringConverter : JsonConverter
    {
        readonly string oldValue;
        readonly string newValue;
    
        public ReplacingStringConverter(string oldValue, string newValue)
        {
            if (string.IsNullOrEmpty(oldValue))
                throw new ArgumentException("string.IsNullOrEmpty(oldValue)");
            if (newValue == null)
                throw new ArgumentNullException("newValue");
            this.oldValue = oldValue;
            this.newValue = newValue;
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var s = (string)JToken.Load(reader);
            return s.Replace(oldValue, newValue);
        }
    
        public override bool CanWrite { get { return false; } }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    Then use it like:

    var settings = new JsonSerializerSettings { Converters = new[] { new ReplacingStringConverter("_", "") } };
    var result = JsonConvert.DeserializeObject(json, settings);
    

    Note however that if individual string-type properties have their own converters applied directly with [JsonConverter(Type)], those converters will be used in preference to the ReplacingStringConverter in the Converters list.

提交回复
热议问题