gpt4 book ai didi

c# - JavaScriptSerializer.Deserialize() 如果无法解析则跳过属性

转载 作者:行者123 更新时间:2023-11-30 22:14:48 25 4
gpt4 key购买 nike

我使用以下代码将 JSON 字符串反序列化为使用 Person 对象:

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

Person 类有一个 Age 属性:

int Age {get;set;}

JSON 字符串的值如下:

{age: 'not valid int'}

我得到如下异常:

Cannot cast string to Int32

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

最佳答案

是的,可以通过编写自定义 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,其中 null 表示年龄未知,但如果这是 Not Acceptable ,您可以将转换器修改为当年龄不可解析时默认为 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);
}

Name: Steve, Age: 21

Name: Teoman, Age:

Name: Queen Elizabeth II, Age: 89

请注意,我们在这里处理了:文字数字、字符串中的数字和完全无效的值。

关于c# - JavaScriptSerializer.Deserialize() 如果无法解析则跳过属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18319491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com