Json.net捕获重复项并引发错误 [英] Json.net catching duplicates and throwing an error

查看:113
本文介绍了Json.net捕获重复项并引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Json.NET(Newtonsoft.Json)-具有两个属性"同一个名字?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆