2016-04-23 67 views
0

我的JSON文件中的重复值:如何检查和抛出一个异常,如果在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" 
    } 
] 

的“诺姆”值都必须是唯一的;我应该做哪种扫描?浏览数组并比较,看看它是否已经存在?我目前正在使用Newtonsoft.Json;有没有帮助功能?

+1

此问题已被回答之前http://stackoverflow.com/questions/3877526/json-net-newtonsoft-json-two-properties-with-same-name http://stackoverflow.com/questions/12806080/json-net-catching-duplicates-and-throw-an-error – JazzCat

+0

@JazzCat这些问题处理JSON中的重复*键*,而这个问题似乎在询问重复的*值* –

回答

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

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

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); 
} 
//... 

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

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

相关问题