J'ai json suivant dans un fichier 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" }
Je souhaite rechercher une clé particulière, par exemple "Atlantic/Canary" de celui-ci et, par conséquent, veulent récupérer sa valeur, c'est-à-dire "GMT Standard Time".
Comment puis-je faire cela en utilisant Json.Net ou tout autre moyen efficace en C #?
Utilisez un analyseur JSON, comme 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>();
Vous voulez d'abord le convertir en objet, puis y accéder normalement en vous assurant de le caster.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];