![](/img/trans.png)
[英]Why is JsonConvert throwing exception when deserializing to a dictionary
[英]How to throw an exception when member comes twice on Deserializing with JsonConvert
我有 JSON ,其中包含重复的成员:
[
{
"MyProperty": "MyProperty1",
"MyProperty": "MyWrongProperty1",
"MyProperty2": "MyProperty12",
"MyProperty2": "MyWrongProperty2"
},
{
"MyProperty": "MyProperty21",
"MyProperty2": "MyProperty22"
}
]
当我反序列化时,它正在获取最后一个属性。 这是代码:
var myJson = File.ReadAllText("1.txt");
List<MyClass> myClasses = JsonConvert.DeserializeObject<List<MyClass>>(myJson);
但是当 JSON 字符串包含重复的属性时,我需要抛出异常。 我怎样才能做到这一点?
您可以使用Newtonsoft.Json
中的JsonTextReader
来获取属于PropertyName
的所有令牌,然后可能使用 LINQ GroupBy()
之类的
string json = "[
{
"MyProperty": "MyProperty1",
"MyProperty": "MyWrongProperty1",
"MyProperty2": "MyProperty12",
"MyProperty2": "MyWrongProperty2"
},
{
"MyProperty": "MyProperty21",
"MyProperty2": "MyProperty22"
}
]";
List<string> props = new List<string>();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null && reader.TokenType == "PropertyName")
{
props.Add(reader.Value);
}
}
现在在列表中使用GroupBy()
来查看重复项
var data = props.GroupBy(x => x).Select(x => new
{
PropName = x.Key,
Occurence = x.Count()
}).Where(y => y.Occurence > 1).ToList();
If (data.Any())
{
Throw New Exception("Duplicate Property Found");
}
这里是 go:
public object DeserializeObject(string json)
{
using (var stringReader = new StringReader(json))
using (var jsonReader = new JsonTextReader(stringReader))
{
return JToken.ReadFrom(jsonReader,
new JsonLoadSettings{ DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error })
.ToObject<object>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.