如果JSON文件中存在重复值,如何检查并抛出异常

时间:2016-04-23 00:18:34

标签: c# json json.net

我的JSON文件:

[
  {
    "nome": "Marcos",
    "pontos": 12,
    "acesso": "2016-04-22T21:10:00.2874904-03:00"
  },
  {
    "nome": "Felipe",
    "pontos": 12,
    "acesso": "2016-04-22T21:10:00.2904923-03:00"
  },
  {
    "nome": "Augusto",
    "pontos": 15,
    "acesso": "2016-04-22T21:10:00.2909925-03:00"
  },
  {
    "nome": "Augusto",
    "pontos": 12,
    "acesso": "2016-04-22T21:10:00.2909925-03:00"
  }
]

" nome"价值必须都是独一无二的;我应该扫描哪个?浏览数组并进行比较以查看它是否已存在?我目前正在使用Newtonsoft.Json;这有什么辅助功能吗?

3 个答案:

答案 0 :(得分:1)

如果存在重复值,生成异常的一种简单方法是尝试将它们放入字典中:

JArray array = JArray.Parse(json);

// This will throw an exception if there are duplicate "nome" values.
array.Select(jt => jt["nome"]).ToDictionary(jt => (string)jt);

这是一个有效的演示:https://dotnetfiddle.net/FSuoem

答案 1 :(得分:0)

你的问题非常具体。因为您首先需要先解析Json数据。我建议您使用System.Collections.Generic.HashSet来验证此类规则。

//...
// Here you do your Json parse with you library:
//Then you need to iterate into the object adding those name values into a HashSet:
System.Collections.Generic.HashSet<String> names = new System.Collections.Generic.HashSet<string> ();
foreach (string name in ITERATE_HERE) {
    if (names.Contains (name)) {
        throw new System.ArgumentException("The name value need to be unique.", "some rule");
    }
    names.Add (name);
}
//...

所以,我希望这可以帮助你。

答案 2 :(得分:0)

假设您有一个JSON输入的模型,如下所示:

public class Model {
    public string Nome { get; set; }
    public string Pontos { get; set; }
    public DateTime Acesso { get; set; }
}

确定是否找到重复项变得非常容易。

var deserialized = JsonConvert.DeserializeObject<List<Model>>(json);

if (deserialized.Select(x => x.Nome).Distinct().Count() != deserialized.Count) {
    throw new Exception("Duplicate names found");
}

如果反序列化列表中的对象数量不等于我们从同一列表中选择的不同名称的数量,我们知道存在重复。