【问题标题】:Parse json string to find and element (key / value) [duplicate]解析json字符串以查找和元素(键/值)[重复]
【发布时间】:2014-03-07 20:07:30
【问题描述】:

我在 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" }

我想搜索一个特定的键,例如来自它的“大西洋/金丝雀”,因此想要它的价值,即“GMT标准时间”。

如何使用 Json.Net 或 C# 中的任何其他有效手段来做到这一点?

【问题讨论】:

标签: c# parsing json.net


【解决方案1】:

您想先将其转换为对象,然后正常访问并确保将其转换。

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

【讨论】:

  • 如果Json上有很多“名字”怎么办?
  • @alansiqueira27 那么它不是 JSON。键必须是唯一的
  • 我认为他可能是指一个 JSON 对象数组,然后会有多个名称
  • 你能添加完整的“使用”语句和/或包引用吗?
【解决方案2】:

使用 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>();

【讨论】:

  • 如果 json 很长,只需要其中的一个键,效率不高
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 2014-09-27
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多