0

My JSON file:

[
  {
    "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"
  }
]

The "nome" values must all be unique; which scan should I do? Go through the array and compare to see if it already exists? I'm currently using Newtonsoft.Json; is there any helper function for this?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • 1
    This question has already been answered before http://stackoverflow.com/questions/3877526/json-net-newtonsoft-json-two-properties-with-same-name http://stackoverflow.com/questions/12806080/json-net-catching-duplicates-and-throwing-an-error – JazzCat Apr 23 '16 at 00:29
  • @JazzCat Those questions deal with duplicate *keys* in the JSON, whereas this question seems to be asking about duplicate *values* – Brian Rogers Apr 23 '16 at 00:38

3 Answers3

1

One easy way to generate an exception if there are duplicate values is to try to put them into a dictionary:

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

Here is a working demo: https://dotnetfiddle.net/FSuoem

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
0

your problem is very specific. Because you need first do a parse of your Json data first. I recommend you to use System.Collections.Generic.HashSet to validate such rule.

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

So, i hope that may can help you.

Timoshenko
  • 26
  • 5
0

Assuming you have a model for your JSON input like so:

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

It becomes quite easy to determine if duplicates are found.

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

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

We know there are duplicates if the number of objects in our deserialized list is not equal to the number of distinct names we selected from the same list.

Connor
  • 807
  • 1
  • 10
  • 20