是的,可以通过编写自定义JavaScriptConverter类来控制反序列化过程:
public class PersonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
Person person = new Person();
foreach (string key in dictionary.Keys)
{
var value = dictionary[key];
switch (key)
{
case "Name":
person.Name = (string)value;
break;
case "Age":
{
if (value is int)
{
person.Age = (int)value;
}
else
{
int age;
if (int.TryParse((string)dictionary[key], out age))
{
person.Age = age;
} // else leave Age as null (or if int, leave as 0); alternatively put an else block here to set to value of your choice
}
}
break;
}
}
return person;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { typeof(Person) };
}
}
}
我冒昧地将其设为Person.Age
可空,其中null
表示年龄未知,但如果这是不可接受的,您可以在年龄不可解析时将转换器修改为默认为 0 或 -1:
public class Person
{
public string Name { get; set; }
public int? Age { get; set; }
}
用法:
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });
var person = serializer.Deserialize<Person>(jsonString);
输出示例:
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });
var jsonStrings = new List<string>
{
"{ Name: 'Steve', Age: 21 }",
"{ Name: 'Teoman', Age: 'not valid int'}",
"{ Name: 'Queen Elizabeth II', Age: '89'}"
};
foreach (var jsonString in jsonStrings)
{
var person = serializer.Deserialize<Person>(jsonString);
Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
}
姓名:史蒂夫,年龄:21
姓名:特奥曼,年龄:
姓名:英国女王伊丽莎白二世,年龄:89
请注意,我们在这里处理了:文字数字、字符串中的数字和完全无效的值。