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.
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
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"];
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.