当成员在使用 JsonConvert 反序列化时出现两次时如何抛出异常

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() like

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");
}

您需要在 JsonLoadSettings 中添加 DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error

您可以按照此 深入挖掘细节。

还有一个来自 Newtonsoft.json 的线程涵盖了 this 个主题。