我使用 Newtonsoft.Json 库
有没有办法在反序列化期间从任何字符串数据中修剪空格?
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);
}
}
添加:
最后,我有了自定义转换器的解决方案。不好,但比使用 Trim() 的属性更好。
如果有人有任何想法如何以更自然的方式做到这一点,请欢迎。
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);
}
}