简体   繁体   中英

How to Deserialize the dictionary and fetch the value of a particular key

How should I get the value of status key?

string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\""

tried with JObject.Parse and JArray.Parse to deserialize it and fetch the value. getting error all the time, even if the key is present.

PS: this value is coming directly from the DB, where it is stored as a string.

Maybe there is a better solution. But you can remove the / character and split by "

string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var val=a.Replace("\\", "").Split(new string[] { "\"" },
StringSplitOptions.None)[4];
using System.Text.Json;

string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var json = JsonDocument.Parse(a).RootElement.GetString();
var jDoc = JsonDocument.Parse(json);
var dic = jDoc.RootElement[0].Deserialize<Dictionary<string, string>>();
var status = dic["Status"];

Here is a method can get the value, hope it can give you some help.

using Newtonsoft.Json;

string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var b = JsonConvert.DeserializeObject(a);
var c = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(b.ToString());

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM