我正在使用C#
反序列化JSON字符串的集合。每个字符串都有一个employer_normalized
属性,该属性应该包含string
和List<int>
,其中List
中的值始终为正。在某些情况下,employer_normalized
设置为-1
,因此我想通过将employer_normalized
设置为null
的某些行为来覆盖这些情况。
这是我的课:
public class EmployerNormalized
{
public string company;
public List<int> code;
}
好的JSON
"employer_normalized": {
"company": "self",
"code": [
"4581 ",
"6732 ",
"9121",
"9999 ",
"5947 ",
"8322 ",
"8351 ",
"7335 ",
"9999 ",
"4225 ",
"8399 "
]
}
JSON错误
"employer_normalized": -1
我目前正在使用
Json.NET
进行JSON解析。解决此问题的最佳解决方案是什么?如果是employer_normalized
,最好只是将null
值设置为-1
吗?如果是这样,我该怎么做? 最佳答案
您可以使用自定义JsonConverter来处理这种情况。无论您在哪里需要EmployerNormalized
,转换器都可以检查该属性的值是否为-1
并返回null,否则可以正常地对其进行反序列化。
这是转换器的代码:
public class EmployerNormalizedConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(EmployerNormalized));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Object)
{
return token.ToObject<EmployerNormalized>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这是演示如何使用它的演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""good"" : {
""company"": ""self"",
""code"": [
""4581 "",
""6732 "",
""9121"",
""9999 "",
""5947 "",
""8322 "",
""8351 "",
""7335 "",
""9999 "",
""4225 "",
""8399 ""
]
},
""bad"" : -1
}";
Wrapper wrapper =
JsonConvert.DeserializeObject<Wrapper>(json,
new EmployerNormalizedConverter());
DumpEmployer("good", wrapper.good);
DumpEmployer("bad", wrapper.bad);
}
private static void DumpEmployer(string prop, EmployerNormalized emp)
{
Console.WriteLine(prop);
if (emp != null)
{
Console.WriteLine(" company: " + emp.company);
Console.WriteLine(" codes: " +
string.Join(", ", emp.code.Select(c => c.ToString())));
}
else
Console.WriteLine(" (null)");
}
public class Wrapper
{
public EmployerNormalized good { get; set; }
public EmployerNormalized bad { get; set; }
}
public class EmployerNormalized
{
public string company;
public List<int> code;
}
}
这是输出:
good
company: self
codes: 4581, 6732, 9121, 9999, 5947, 8322, 8351, 7335, 9999, 4225, 8399
bad
(null)
重要说明:您可能会想用
EmployerNormalized
装饰[JsonConverter(typeof(EmployerNormalizedConverter))]
类,但是如果这样做,转换器将以其当前形式最终递归地调用自身,直到它因StackOverflowException
而出错。如果需要/想要使用该属性,则将需要更改转换器中ReadJson
方法的代码,以便它手动创建EmployerNormalized
类的实例并单独填充其所有属性,而不是调用token.ToObject<EmployerNormalized>()
。这是ReadJson
的替代版本,它将避免递归问题:public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Object)
{
EmployerNormalized employer = new EmployerNormalized();
employer.company = token["company"].ToString();
employer.code = token["code"].ToObject<List<int>>();
return employer;
}
return null;
}