2014-02-10 43 views
6

我有以下的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标准时间”。

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

回答

19

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

谢谢,它的作品像一个魅力:) – theGeekster

10

你想它首先转换为对象,然后访问正常,确保投它。

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