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



我在文件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 标准时间"。

如何在 C# 中使用 Json.Net 或任何其他有效平均值来执行此操作?

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

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

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

相关内容

  • 没有找到相关文章

最新更新