Json.net捕获重复项并引发错误 [英] Json.net catching duplicates and throwing an error
问题描述
Possible Duplicate:
Json.NET (Newtonsoft.Json) - Two 'properties' with same name?
我正在使用JSON.NET将JSON文件反序列化为Dictionary.现在,我要执行的是以下行:
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);
如果JSON中存在重复的条目,则抛出异常,如下所示:
throw an exception if there are duplicate entries in the JSON like this:
{
"ExampleText": "Example 1",
"ExampleText": "Example 2",
"ExampleText": "Example 3",
}
标准的JSON.NET行为是将JSON中最后一个条目替换为"ExampleText"条目.可以抛出异常吗?
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?
推荐答案
-编辑-
您不需要反序列化为IDictionary<string, object>
. JObject
已经实现了IDictionary<string, JToken>
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"];
这篇关于Json.net捕获重复项并引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!