I use Newtonsoft.Json library
Is there a way to trim spaces from any string data during deserialization?
class Program
{
class Person
{
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 "