JavaScriptSerializer.Deserialize()跳过属性,如果无法解析它

时间:2013-08-19 17:20:46

标签: c# .net json javascriptserializer

我正在使用此代码将JSON字符串反序列化为使用Person个对象:

JavaScriptSerializer serializer = new JavaScriptSerializer();
Person person = serializer.Deserialize<Person>(jsonString);

Person类有Age属性:

int Age {get;set;}

JSON字符串的值如下:

  

{age:&#39;无效int&#39;}

我得到如下例外:

  

无法将字符串强制转换为Int32

有没有办法告诉JavaScriptSerializer跳过错误并继续使用其他属性?

1 个答案:

答案 0 :(得分:3)

是的,可以通过编写自定义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

     

姓名:Teoman,年龄:

     

姓名:女王伊丽莎白二世,年龄:89

请注意,我们在此处理过:字面数字,字符串中的数字以及完全无效的值。