1

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.

3
  • you can create a class that represents that... or use the jsondocument way. Commented Aug 21, 2020 at 21:24
  • Make sure that the json is valid, you are missing an ending "" fyi Commented Aug 21, 2020 at 21:26
  • If you only need one value you can parse the json and dig out that one value. no need for a class that way. Gobs and gobs of posts here on both deserializing and parsing. Commented Aug 21, 2020 at 22:11

3 Answers 3

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"];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.