0

I'm working on a Blazor application and I have a Json string from which I'm trying to extract a value.

Json Data looks like this:

{"a1":"a1234","e1":"e1234}

I'm trying to extract the a1 value from this which is "a1234"

My JSON Data is in a string variable, rawJsonData. I'm trying to use the JsonSerializer.Deserialize, but I'm not sure how to completely use it...

@code 
{
    string rawJsonData = JsonData (this is not the actual data, it's being pulled from elsewhere)
    var x = System.Text.Json.JsonSerializer.Deserialize<???>(rawJsonData)
}

is this the right way to approach this? I'm not sure what to put in place of ??? above. Anyone has experience with this.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Koosh
  • 876
  • 13
  • 26

3 Answers3

2

If you use Newtonsoft, as suggested in another answer, you don't even have to create a class.

JObject temp = JObject.Parse(rawJsonData);
var a1 = temp["a1"];
Lex
  • 6,758
  • 2
  • 27
  • 42
1

Create a class:

public class Root
{
   public string a1 { get; set; }
   public string e1 { get; set; }
}

Then Deserialize it into that class:

var x = System.Text.JsonSerializer.Deserialize<Root>(rawJsonData);

Or use Newtonsoft.Json:

var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(rawJsonData);

To retrieve the value of a1 just call: x.a1

jaabh
  • 815
  • 6
  • 22
1

If you want to stick with System.Text.Json and don't want to create a class/struct for the data (why not?), as suggested in comments, you can

var jsonData = "{\"a1\":\"a1234\",\"e1\":\"e1234\"}";
var doc = JsonDocument.Parse(jsonData);
var a1 = doc?.RootElement.GetProperty("a1").GetString();

Of course, a try catch around the conversion would help.

Mister Magoo
  • 7,452
  • 1
  • 20
  • 35