Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

c# - Deserialize json with auto-trimming strings

I use Newtonsoft.Json library

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

class Program
{
    class Person
    {
        [JsonProperty("name")]
        public string Name;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "" }");
        Console.WriteLine("Name is: "{0}"", p.Name);
    }
}

Added:

Finally, I've got solution with custom converter. Not nice, but better then property with Trim().

If anyone has any ideas how to do it in more natural way, please welcome.

class Program
{
    sealed class TrimAttribute : Attribute
    { }

    class TrimConverter<T> : JsonConverter where T : new()
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var obj = new T();
            serializer.Populate(jObject.CreateReader(), obj);

            var props = objectType.GetFields(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.FieldType == typeof(string))
                .Where(p => Attribute.GetCustomAttributes(p).Any(u => (Type) u.TypeId == typeof(TrimAttribute)))
                ;

            foreach (var fieldInfo in props)
            {
                var val = (string) fieldInfo.GetValue(obj);
                fieldInfo.SetValue(obj, val.Trim());
            }

            return obj;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsAssignableFrom(typeof (T));
        }
    }

    [JsonConverter(typeof(TrimConverter<Person>))]
    class Person
    {
        [JsonProperty("name")]
        [Trim]
        public string Name;

        [JsonProperty("surname")]
        public string Surname;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "", surname: "" Smith "" }");
        Console.WriteLine("Name is: "{0}", "{1}"", p.Name, p.Surname);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Person>(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<Person>(json);
Console.WriteLine("Name is: "{0}"", p.Name);
Console.WriteLine("Other is: "{0}"", p.Other);

//Name is: "John"
//Other is: " blah blah blah "

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...