解析json字符串以查找元素(键/值)

43

我有一个名为timezones.json的文件,其中包含以下json:

  { "Atlantic/Canary": "GMT Standard Time", "Europe/Lisbon": "GMT Standard Time", 
"Antarctica/Mawson": "West Asia Standard Time", "Etc/GMT+3": "SA Eastern Standard Time", 
"Etc/GMT+2": "UTC-02", "Etc/GMT+1": "Cape Verde Standard Time", "Etc/GMT+7": "US Mountain 
Standard Time", "Etc/GMT+6": "Central America Standard Time", "Etc/GMT+5": "SA Pacific 
Standard Time", "Etc/GMT+4": "SA Western Standard Time", "Pacific/Wallis": "UTC+12", 
"Europe/Skopje": "Central European Standard Time", "America/Coral_Harbour": "SA Pacific 
Standard Time", "Asia/Dhaka": "Bangladesh Standard Time", "America/St_Lucia": "SA Western 
Standard Time", "Asia/Kashgar": "China Standard Time", "America/Phoenix": "US Mountain 
Standard Time", "Asia/Kuwait": "Arab Standard Time" }

我想从中搜索特定的键,例如“Atlantic/Canary”,并返回其对应的值,即“GMT Standard Time”。

如何使用Json.Net或其他有效的方式在C#中实现这一点?


请查看此处:https://dev59.com/kWox5IYBdhLWcg3wtmrh - Jsperk
2个回答

75

使用JSON解析器,例如JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

4
如果 JSON 很长,而你只需要其中的一个键,那么这种方法并不是很高效。 - Loreno

47

你希望先将其转换为对象,然后正常访问,确保进行强制转换。

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

如果Json中有许多“Name”怎么办? - alansiqueira27
7
那它就不是JSON了。键必须是唯一的。 - Kurtis Streutker
1
我认为他可能是指JSON对象的数组,这将具有多个名称。 - Thomas Clague
你能添加完整的 "using" 语句和/或包引用吗? - granadaCoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接