Home > Software engineering >  How to read JSON value for single value?
How to read JSON value for single value?

Time:09-08

I have an application that returns the below JSON format with only 1 value:

{"isActive":true}

I can read the value by putting it into a dictionary as per below:

var value = JsonSerializer.Deserialize<Dictionary<string, bool>>(rawValue, JsonSerializerSettings.Web)!.value;

But it does not seem to be a good way to use a dictionary to store a single key/value.

Is there a better way to get the value from the JSON?

CodePudding user response:

you can just parse your json

using System.Text.Json;

bool isActive= (bool) JsonNode.Parse(json)["isActive"];

or using Newtonsoft.Json

using Newtonsoft.Json

bool isActive = (bool) JObject.Parse(json)["isActive"];

CodePudding user response:

Assuming your json is returned as a string. You should then use dynamic in your case and it works very well. Below are two methods, you can get what you are looking for:

using Nancy.Json;

string jsonString = "{\"isActive\": true}";
var jsSeralizer = new JavaScriptSerializer();
var jsonTable = jsSeralizer.Deserialize<dynamic>(jsonString);
Console.WriteLine("JSS Is Active? {0}", jsonTable["isActive"]);

OR

using Newtonsoft.Json;

string jsonString = "{\"isActive\": true}";
var dynamicTable = JsonConvert.DeserializeObject<dynamic>(jsonString);
Console.WriteLine("JC Is Active? {0}", dynamicTable["isActive"]);

CodePudding user response:

I think this is useful for you, You can use the HashSet Collections as an alternative to dictionaries for storing a single value.

HashSet<>
  • Related