I have this JSON string:
string jsonString =
"{
"users":[
{"name":"John", "code":"white", "job":"actor"},
{"name":"Oliver", "code":"black", "job": "seller"}
]
}"
then deserialize it using:
JsonElement je = JsonDocument.Parse(jsonString).RootElement;
JsonElement.ArrayEnumerator users = je.GetProperty("users").EnumerateArray();
with system.text.json how can I get first JsonElement whose code is "black"? I mean without loops (foreach, ...).
with newtonsoft.json I could simply do this:
dynamic json = JsonConvert.DeserializeObject(jsonString);
dynamic user = json.SelectToken("[?(@.code == 'black')]");
string name = user["name"], job = user["job"];
how can I get first JsonElement whose code is "black"
I would create classes that represent your json structure and then deserialize to those classes.
You can create your classes as such:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class People
{
[JsonPropertyName("users")]
public List<User> Users { get; set; }
}
public class User
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("code")]
public string Code { get; set; }
[JsonPropertyName("job")]
public string Job { get; set; }
}
Then to deserialize:
string jsonString = "{\"users\":[{\"name\":\"John\",\"code\":\"white\",\"job\":\"actor\"},{\"name\":\"Oliver\",\"code\":\"black\",\"job\":\"seller\"}]}";
People people = JsonSerializer.Deserialize<People>(jsonString);
Now you can get the first User object where code is black:
var usr = people.Users.Where(u => u.Code == "black").FirstOrDefault();
Here's the example you can run.
UPDATE PER COMMENT
it is dynamic JSON
You can deserialize your json to JsonElement and then try and get the properties you want.
var people = JsonSerializer.Deserialize<JsonElement>(jsonString);
if(people is JsonElement je && je.TryGetProperty("users", out je)){
// obj will be JsonElement if match is found
var obj = je.EnumerateArray().Where(je => je.TryGetProperty("code", out je) && je.GetString() == "black").FirstOrDefault();
// Get what you need
var name = obj.TryGetProperty("name", out JsonElement eleName) ? eleName.GetString() : "No name";
var job = obj.TryGetProperty("job", out JsonElement eleJob) ? eleJob.GetString() : "No job";
Console.WriteLine(string.Format("{0}\n{1}", name, job));
}
*You can test this code there