title: Deserialize json with auto-trimming strings
body: <p>I use Newtonsoft.Json library</p>
  
  <p>Is there a way to trim spaces from any string data during deserialization?</p>
  
  <pre><code>class Program
  {
      class Person
      {
          [JsonProperty("name")]
          public string Name;
      }
      static void Main(string[] args)
      {
          var p = JsonConvert.DeserializeObject&lt;Person&gt;(@"{ name: "" John "" }");
          Console.WriteLine("Name is: \"{0}\"", p.Name);
      }
  }
  </code></pre>
  
  <p>Added:</p>
  
  <p>Finally, I've got solution with custom converter. Not nice, but better then property with Trim().</p>
  
  <p>If anyone has any ideas how to do it in more natural way, please welcome.</p>
  
  <pre><code>class Program
  {
      sealed class TrimAttribute : Attribute
      { }
  
      class TrimConverter&lt;T&gt; : 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 =&gt; p.FieldType == typeof(string))
                  .Where(p =&gt; Attribute.GetCustomAttributes(p).Any(u =&gt; (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&lt;Person&gt;))]
      class Person
      {
          [JsonProperty("name")]
          [Trim]
          public string Name;
  
          [JsonProperty("surname")]
          public string Surname;
      }
      static void Main(string[] args)
      {
          var p = JsonConvert.DeserializeObject&lt;Person&gt;(@"{ name: "" John "", surname: "" Smith "" }");
          Console.WriteLine("Name is: \"{0}\", \"{1}\"", p.Name, p.Surname);
      }
  }
  </code></pre>