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

Time:02-01

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.

CodePudding user response:

using Newtonsoft.Json.Linq;

...

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

// Remove the extra quotes at the beginning and end of the string
a = a.Trim('\"');

// Parse the string into a JArray
JArray array = JArray.Parse(a);

// Get the first element in the array (the only element in this case)
JObject obj = (JObject)array[0];

// Get the value of the "Status" key
string status = (string)obj["Status"];

// Output the value of the "Status" key
Console.WriteLine(status); // Output: Passed

CodePudding user response:

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];
  • Related