Parse json string to find and element (key / value

2020-02-08 07:47发布

问题:

This question already has answers here:
Closed 5 years ago.

I have following json in a file timezones.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" }

I want to search for a particular key e.g. "Atlantic/Canary" from it and as a result want its value back i.e. "GMT Standard Time".

How can I do this using Json.Net or any other efficient mean in C#?

回答1:

Use a JSON parser, like 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>();


回答2:

You want to convert it to an object first and then access normally making sure to cast it.

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