0

Possible Duplicate:
Json.NET (Newtonsoft.Json) - Two 'properties' with same name?

I'm using JSON.NET to deserialize a JSON file into a Dictionary. Now what I'd like to do is have the following line:

JsonConvert.DeserializeObject<IDictionary<string, object>>(text);

throw an exception if there are duplicate entries in the JSON like this:

{
    "ExampleText": "Example 1",
    "ExampleText": "Example 2",
    "ExampleText": "Example 3",
}

The standard JSON.NET behavior is to simply replace the "ExampleText" entry with whichever entry is last in the JSON. Is it possible to have the exception thrown instead?

Community
  • 1
  • 1
shaqua471
  • 11
  • 4
  • 1
    It's not a duplicate. He wanted to support deserialization even though he had multiple entries with the same key. What I want is instead of just a replacement of the single TBox entry, I want an exception to be thrown telling me there are duplicate entries for the same key. – shaqua471 Oct 09 '12 at 21:32
  • I actually found a way to do what I wanted but I had to use JsonTextReader to parse each token myself. It feels a little dirty but it allows me to insure that an exception gets thrown in the case of a duplicate entry. – shaqua471 Oct 09 '12 at 21:35
  • This isn't a duplicate at all. This is the answer: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_DuplicatePropertyNameHandling.htm – Rob Sedgwick Oct 02 '19 at 14:16

2 Answers2

0

If you look to IDictionary in msdn

"Each association must have a unique key"

Your problem in duplicated keys. I think you should use another collection.

Try this

class MyValue
{
  public string Key {get; set;}
  public string Value {get; set;}
}

JsonConvert.DeserializeObject<List<MyValue>>(text);
Sanja Melnichuk
  • 3,465
  • 3
  • 25
  • 46
  • Have you tried to deserialize the json in question to `List>` ? – L.B Oct 09 '12 at 19:23
  • You can't deserialize into .NET List. You'll get this error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]]' – shaqua471 Oct 09 '12 at 19:27
0

--EDIT--

You dont need to deserialize to IDictionary<string, object>. JObject already implements IDictionary<string, JToken>

var obj = (JObject)JsonConvert.DeserializeObject(json); //will throw exception for dublicates.
var str = (string)obj["ExampleText"];
L.B
  • 114,136
  • 19
  • 178
  • 224