Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
system.text.json search a dynamic json

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"];
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda