1

我有包含重复成员的 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 字符串包含重复的属性时,我需要抛出异常。我怎样才能做到这一点?

4

2 回答 2

2

您可以使用JsonTextReaderfromNewtonsoft.Json来获取所有令牌,PropertyName然后可能使用GroupBy()LINQ

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");
}
于 2020-05-16T08:33:55.573 回答
2

您需要DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error在您的JsonLoadSettings.

您可以在this answer之后详细了解。

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

于 2020-05-16T08:41:28.570 回答