1

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Vida
  • 89
  • 1
  • 8
  • You could deserialize to an anonymous type `new { isActive = default(bool) }`. See: [Deserialize anonymous type with System.Text.Json](https://stackoverflow.com/q/59313256/3744182). For Json.NET see [Deserialize an Anonymous Type](https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm). – dbc Dec 13 '22 at 18:16

3 Answers3

3

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"];
Serge
  • 40,935
  • 4
  • 18
  • 45
-1

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"]);
imk
  • 1
  • 2
  • [`JavaScriptSerializer`](https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer?view=netframework-4.8#remarks) is obsolete and was never ported to .NET Core. – dbc Dec 13 '22 at 18:17
-1

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

HashSet<>