2016-04-23 68 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

相關問題