- Artigo
Este artigo mostra como usar umModelo de objeto de documento JSON (DOM)para acesso aleatório aos dados em uma carga JSON.
Opções JSON DOM
Trabalhar com um DOM é uma alternativa à desserialização comJsonSerializerquando:
- Você não tem um tipo para desserializar.
- O JSON que você recebe não possui um esquema fixo e deve ser inspecionado para saber o que ele contém.
System.Text.Json
fornece duas maneiras de criar um JSON DOM:
JsonDocumentNamefornece a capacidade de criar um DOM somente leitura usando
Utf8JsonReaderName
. Os elementos JSON que compõem o payload podem ser acessados por meio doJsonElementNametipo. OJsonElementName
type fornece enumeradores de matriz e objeto junto com APIs para converter texto JSON em tipos .NET comuns.JsonDocumentName
expõe umRaizElementopropriedade. Para mais informações, vejaUsar JsonDocumentposteriormente neste artigo.JsonNodee as classes que dela derivam noSystem.Text.Json.Nodesnamespace fornecem a capacidade de criar um DOM mutável. Os elementos JSON que compõem o payload podem ser acessados por meio doJsonNode,JsonObject,JsonArray,JsonValue, eJsonElementNametipos. Para mais informações, vejaUsar JsonNodeposteriormente neste artigo.
(Video) 40% faster JSON serialization with Source Generators in .NET 6
Considere os seguintes fatores ao escolher entreJsonDocumentName
eJsonNode
:
- O
JsonNode
O DOM pode ser alterado depois de criado. OJsonDocumentName
DOM é imutável. - O
JsonDocumentName
O DOM fornece acesso mais rápido aos seus dados.
UsarJsonNode
O exemplo a seguir mostra como usarJsonNodee os outros tipos noSystem.Text.Json.Nodesespaço de nomes para:
- Crie um DOM a partir de uma string JSON
- Escreva JSON de um DOM.
- Obtenha um valor, objeto ou array de um DOM.
using System.Text.Json;using System.Text.Json.Nodes;namespace JsonNodeFromStringExample;public class Program{ public static void Main() { string jsonString =@"{ ""Date"": ""2019-08-01T00: 00:00"", ""Temperatura"": 25, ""Resumo"": ""Quente"", ""Datas disponíveis"": [ ""2019-08-01T00:00:00"", ""2019 -08-02T00:00:00"" ], ""Faixas de temperatura"": { ""Frio"": { ""Alto"": 20, ""Baixo"": -10 }, ""Quente"": { ""Alto"": 60, ""Baixo"": 20 } }}"; // Cria um DOM JsonNode a partir de uma string JSON. JsonNode forecastNode = JsonNode.Parse(jsonString)!; // Escreve JSON de um JsonNode var options = new JsonSerializerOptions { WriteIndented = true }; Console.WriteLine(forecastNode!.ToJsonString(opções)); // saída: //{ // "Data": "2019-08-01T00:00:00", // "Temperatura": 25, // "Resumo": "Quente", // "Datas disponíveis": [ // "2019-08-01T00:00:00", // "2019-08-02T00:00:00" // ], // "Temperature Ranges": { // "Frio": { // "Alto" : 20, // "Baixo": -10 // }, // "Quente": { // "Alto": 60, // "Baixo": 20 // } // } //} // Obter valor de um JsonNode. JsonNode temperatureNode = forecastNode!["Temperatura"]!; Console.WriteLine($"Type={temperatureNode.GetType()}"); Console.WriteLine($"JSON={temperatureNode.ToJsonString()}"); //output: //Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement] //JSON = 25 // Obtém um valor digitado de um JsonNode. int temperatureInt = (int)forecastNode!["Temperatura"]!; Console.WriteLine($"Value={temperatureInt}"); //output: //Value=25 // Obtém um valor digitado de um JsonNode usando GetValue. temperatureInt = forecastNode!["Temperatura"]!.GetValue(); Console.WriteLine($"TemperatureInt={temperatureInt}"); //output: //Value=25 // Obtém um objeto JSON de um JsonNode. JsonNode temperatureRanges = forecastNode!["TemperatureRanges"]!; Console.WriteLine($"Type={temperatureRanges.GetType()}"); Console.WriteLine($"JSON={temperatureRanges.ToJsonString()}"); //output: //Type = System.Text.Json.Nodes.JsonObject //JSON = { "Cold":{ "High":20,"Low":-10},"Hot":{ "High": 60,"Low":20} } // Obtém um array JSON de um JsonNode. JsonNode dateAvailable = forecastNode!["DatesDisponível"]!; Console.WriteLine($"Type={datesAvailable.GetType()}"); Console.WriteLine($"JSON={datesAvailable.ToJsonString()}"); //output: //datesAvailable Type = System.Text.Json.Nodes.JsonArray //datesAvailable JSON =["2019-08-01T00:00:00", "2019-08-02T00:00:00"] // Obtenha um valor de elemento de matriz de um JsonArray. JsonNode firstDateAvailable = dateAvailable[0]!; Console.WriteLine($"Type={firstDateAvailable.GetType()}"); Console.WriteLine($"JSON={firstDateAvailable.ToJsonString()}"); //output: //Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement] //JSON = "2019-08-01T00:00:00" // Obtém um valor digitado por encadeamento de referências. int coldHighTemperature = (int)forecastNode["Intervalos de temperatura"]!["Frio"]!["Alto"]!; Console.WriteLine($"TemperatureRanges.Cold.High={coldHighTemperature}"); //saída: //TemperatureRanges.Cold.High = 20 // Analisa um array JSON var dateNode = JsonNode.Parse(@"[""2019-08-01T00:00:00"",""2019-08-02T00 :00:00""]"); JsonNode firstDate = dateNode![0]!.GetValue(); Console.WriteLine($"firstDate={ firstDate}"); //output: //firstDate = "2019-08-01T00:00:00" }}
Crie um DOM JsonNode com inicializadores de objeto e faça alterações
O exemplo a seguir mostra como:
- Crie um DOM usando inicializadores de objeto.
- Faça alterações em um DOM.
using System.Text.Json;using System.Text.Json.Nodes;namespace JsonNodeFromObjectExample;public class Program{ public static void Main() { // Crie um novo JsonObject usando inicializadores de objeto. var forecastObject = new JsonObject { ["Date"] = new DateTime(2019, 8, 1), ["Temperature"] = 25, ["Summary"] = "Hot", ["DatesAvailable"] = new JsonArray( new DateTime(2019, 8, 1), new DateTime(2019, 8, 2)), ["TemperatureRanges"] = new JsonObject { ["Cold"] = new JsonObject { ["High"] = 20, ["Low" ] = -10 } }, ["SummaryWords"] = new JsonArray("Cool", "Windy", "Humid") }; // Adicionar um objeto. forecastObject!["TemperatureRanges"]!["Hot"] = new JsonObject { ["High"] = 60, ["Low"] = 20 }; // Remove uma propriedade. previsãoObject.Remove("SummaryWords"); // Altera o valor de uma propriedade. forecastObject["Date"] = new DateTime(2019, 8, 3); var opções = new JsonSerializerOptions { WriteIndented = true }; Console.WriteLine(forecastObject.ToJsonString(opções)); //saída: //{ // "Data": "2019-08-03T00:00:00", // "Temperatura": 25, // "Resumo": "Quente", // "Datas disponíveis": [ // "2019-08-01T00:00:00", // "2019-08-02T00:00:00" // ], // "Temperature Ranges": { // "Frio": { // "Alto" : 20, // "Baixo": -10 // }, // "Quente": { // "Alto": 60, // "Baixo": 20 // } // } //} }}
Desserializar subseções de uma carga JSON
O exemplo a seguir mostra como usarJsonNodepara navegar para uma subseção de uma árvore JSON e desserializar um único valor, um tipo personalizado ou uma matriz dessa subseção.
usando System.Text.Json;usando System.Text.Json.Nodes;namespace JsonNodePOCOExample;public class TemperatureRanges : Dictionary{}public class HighLowTemps{ public int High { get; definir; } public int Baixa { obter; definir; }}Programa de classe pública{ public static DateTime[]? Datas disponíveis { get; definir; } public static void Main() { string jsonString =@"{ ""Data"": ""2019-08-01T00:00:00"", ""Temperatura"": 25, ""Resumo"": "" Quente"", ""Datas disponíveis"": [ ""2019-08-01T00:00:00"", ""2019-08-02T00:00:00"" ], ""Temperature Ranges"": { ""Frio "": { ""Alta"": 20, ""Baixa"": -10 }, ""Quente"": { ""Alta"": 60, ""Baixa"": 20 } }}"; // Analisa todo o JSON. JsonNode forecastNode = JsonNode.Parse(jsonString)!; // Obtém um único valor int hotHigh = forecastNode["TemperatureRanges"]!["Hot"]!["High"]!.GetValue(); Console.WriteLine($"Hot.High={hotHigh}"); // output: //Hot.High=60 // Obtenha uma subseção e desserialize-a em um tipo personalizado. JsonObject temperatureRangesObject = forecastNode!["TemperatureRanges"]!.AsObject(); usando var stream = new MemoryStream(); usando var Writer = new Utf8JsonWriter(stream); temperatureRangesObject.WriteTo(escritor); escritor.Flush(); Faixas de temperatura? temperatureRanges = JsonSerializer.Deserialize(stream.ToArray()); Console.WriteLine($"Cold.Low={temperatureRanges!["Cold"].Baixo}, Hot.High={temperatureRanges["Hot"].Alto}"); // output: //Cold.Low=-10, Hot.High=60 // Obtenha uma subseção e desserialize-a em um array. JsonArray dateAvailable = forecastNode!["DatesAvailable"]!.AsArray()!; Console.WriteLine($"Datas disponíveis[0]={datas disponíveis[0]}"); // saída: //Datas disponíveis[0]=01/08/2019 12:00:00 }}
Exemplo de nota média JsonNode
O exemplo a seguir seleciona uma matriz JSON que possui valores inteiros e calcula um valor médio:
using System.Text.Json.Nodes;namespace JsonNodeAverageGradeExample;public class Program{ public static void Main() { string jsonString =@"{ ""Nome da turma"": ""Ciência"", ""Nome do professor"" : ""Jane"", ""Semestre"": ""01-01-2019"", ""Estudantes"": [ { ""Nome"": ""João"", ""Nota"": 94,3 }, { ""Nome"": ""James"", ""Nota"": 81,0 }, { ""Nome"": ""Julia"", ""Nota"": 91,9 }, { ""Nome "": ""Jessica"", ""Nota"": 72,4 }, { ""Nome"": ""Johnathan"" } ], ""Final"": verdadeiro}"; dupla soma = 0; contagem int = 0; documento JsonNode = JsonNode.Parse(jsonString)!; JsonNode root = document.Root; JsonArray alunosArray = root["Alunos"]!.AsArray(); contagem = alunosArray.Count; foreach (JsonNode? aluno em alunosArray) { if (aluno?["Nota"] é JsonNode notaNode) { soma += (duplo) notaNode; } else { soma += 70; } } média dupla = soma / contagem; Console.WriteLine($"Nota média: {média}"); }}// output://Nota média: 81,92
O código anterior:
- Calcula uma nota média para objetos em um
Alunos
matriz que tem umNota
propriedade. - Atribui uma nota padrão de 70 para os alunos que não têm nota.
- Obtém o número de alunos do
Contar
propriedade deJsonArray
.
JsonNode
comJsonSerializerOptions
Você pode usarJsonSerializer
para serializar e desserializar uma instância deJsonNode
. No entanto, se você usar uma sobrecarga que levaJsonSerializerOptions
, a instância de opções é usada apenas para obter conversores personalizados. Outros recursos da instância de opções não são usados. Por exemplo, se você definirJsonSerializerOptions.DefaultIgnoreConditionparaWhenWritingNulle ligueJsonSerializer
com uma sobrecarga que levaJsonSerializerOptions
, as propriedades nulas não serão ignoradas.
A mesma limitação se aplica aoJsonNode
métodos que levam umJsonSerializerOptions
parâmetro:WriteTo(Utf8JsonWriter, JsonSerializerOptions)eToJsonString(JsonSerializerOptions). Essas APIs usamJsonSerializerOptions
apenas para obter conversores personalizados.
O exemplo a seguir ilustra o resultado do uso de métodos que usam umJsonSerializerOptions
parâmetro e serializar umJsonNode
instância:
usando System.Text;usando System.Text.Json;usando System.Text.Json.Nodes;usando System.Text.Json.Serialization;namespace JsonNodeWithJsonSerializerOptions;public class Program{ public static void Main() { Person person = new Person { Nome = "Nancy" }; // Serialização padrão - Propriedade de endereço incluída no token nulo. // Output: {"Name":"Nancy","Address":null} string personJsonWithNull = JsonSerializer.Serialize(person); Console.WriteLine(pessoaJsonWithNull); // Serialize e ignore propriedades nulas - a propriedade de endereço nula é omitida // Saída: {"Name":"Nancy"} JsonSerializerOptions options = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; string pessoaJsonWithoutNull = JsonSerializer.Serialize(pessoa, opções); Console.WriteLine(pessoaJsonWithoutNull); // Ignorar propriedades nulas não funciona ao serializar a instância JsonNode // usando JsonSerializer. // Output: {"Name":"Nancy","Address":null} var personJsonNode = JsonSerializer.Deserialize(personJsonWithNull); personJsonWithNull = JsonSerializer.Serialize(personJsonNode, opções); Console.WriteLine(pessoaJsonWithNull); // Ignorar propriedades nulas não funciona ao serializar a instância JsonNode // usando o método JsonNode.ToJsonString. // Output: {"Name":"Nancy","Address":null} personJsonWithNull = personJsonNode!.ToJsonString(options); Console.WriteLine(pessoaJsonWithNull); // Ignorar propriedades nulas não funciona ao serializar a instância JsonNode // usando o método JsonNode.WriteTo. // Output: {"Name":"Nancy","Address":null} using var stream = new MemoryStream(); usando var Writer = new Utf8JsonWriter(stream); personJsonNode!.WriteTo(escritor, opções); escritor.Flush(); personJsonWithNull = Encoding.UTF8.GetString(stream.ToArray()); Console.WriteLine(pessoaJsonWithNull); }}public class Person{ public string? Nome { obter; definir; } string pública? Endereço { obter; definir; }}
Se você precisa de recursos deJsonSerializerOptions
exceto conversores personalizados, useJsonSerializer
com alvos fortemente tipados (como oPessoa
classe neste exemplo) em vez deJsonNode
.
UsarJsonDocumentName
O exemplo a seguir mostra como usar oJsonDocumentNameclass para acesso aleatório aos dados em uma string JSON:
soma dupla = 0;contagem int = 0;usando (JsonDocument document = JsonDocument.Parse(jsonString)){ JsonElement root = document.RootElement; JsonElement StudentsElement = root.GetProperty("Estudantes"); foreach (JsonElement aluno em alunosElement.EnumerateArray()) { if (aluno.TryGetProperty("Grade", out JsonElement gradeElement)) { soma += gradeElement.GetDouble(); } else { soma += 70; } contagem++; }}dupla média = soma / contagem;Console.WriteLine($"Nota média : {média}");
Dim sum As Double = 0Dim count As Integer = 0Using document As JsonDocument = JsonDocument.Parse(jsonString) Dim root As JsonElement = document.RootElement Dim StudentsElement As JsonElement = root.GetProperty("Students") For Each student As JsonElement In StudentsElement. EnumerateArray() Dim gradeElement As JsonElement = Nothing If student.TryGetProperty("Grade", gradeElement) Then sum += gradeElement.GetDouble() Else sum += 70 End If count += 1 NextEnd UsingDim average As Double = sum / countConsole. WriteLine($"Nota média: {média}")
O código anterior:
- Assume que o JSON a ser analisado está em uma string chamada
jsonString
. - Calcula uma nota média para objetos em um
Alunos
matriz que tem umNota
propriedade. - Atribui uma nota padrão de 70 para os alunos que não têm nota.
- Cria o
JsonDocumentName
instância em umusando declaraçãoporqueJsonDocumentName
implementosIDisposable
. Após umJsonDocumentName
instância é descartada, você perde o acesso a todos os seusJsonElementName
instâncias também. Para manter o acesso a umJsonElementName
exemplo, faça uma cópia antes que o paiJsonDocumentName
instância é descartada. Para fazer uma cópia, ligueJsonElement.Clone. Para mais informações, vejaJsonDocument é IDisposable.
O código de exemplo anterior conta os alunos incrementando umcontar
variável a cada iteração. Uma alternativa é ligarGetArrayLength, conforme o exemplo a seguir:
soma dupla = 0;contagem int = 0;usando (JsonDocument document = JsonDocument.Parse(jsonString)){ JsonElement root = document.RootElement; JsonElement StudentsElement = root.GetProperty("Estudantes"); contagem = alunosElemento.GetArrayLength(); foreach (JsonElement aluno em alunosElement.EnumerateArray()) { if (aluno.TryGetProperty("Grade", out JsonElement gradeElement)) { soma += gradeElement.GetDouble(); } else { soma += 70; } }}dupla média = soma / contagem;Console.WriteLine($"Nota média : {média}");
Dim sum As Double = 0Dim count As Integer = 0Using document As JsonDocument = JsonDocument.Parse(jsonString) Dim root As JsonElement = document.RootElement Dim StudentsElement As JsonElement = root.GetProperty("Students") count = StudentsElement.GetArrayLength() For Cada aluno As JsonElement In StudentsElement.EnumerateArray() Dim gradeElement As JsonElement = Nothing If student.TryGetProperty("Grade", gradeElement) Then sum += gradeElement.GetDouble() Else sum += 70 End If NextEnd UsingDim average As Double = sum / countConsole.WriteLine($"Nota média: {média}")
Aqui está um exemplo do JSON que este código processa:
{ "Class Name": "Science", "Teacher\u0027s Name": "Jane", "Semestre": "2019-01-01", "Students": [ { "Name": "John", "Grade" : 94,3 }, { "Nome": "James", "Grade": 81,0 }, { "Nome": "Julia", "Grade": 91,9 }, { "Nome": "Jessica", "Grade": 72,4 }, { "Nome": "Johnathan" } ], "Final": verdadeiro}
Para um exemplo semelhante que usaJsonNode
em vez deJsonDocumentName
, verExemplo de nota média JsonNode.
Como pesquisar um JsonDocument e JsonElement para subelementos
Pesquisas emJsonElementName
exigem uma pesquisa sequencial das propriedades e, portanto, são relativamente lentos (por exemplo, ao usarTryGetProperty
).System.Text.Jsonfoi projetado para minimizar o tempo de análise inicial em vez do tempo de pesquisa. Portanto, use as seguintes abordagens para otimizar o desempenho ao pesquisar em umJsonDocumentName
objeto:
- Use os enumeradores integrados (EnumerateArrayeEnumerateObject) em vez de fazer sua própria indexação ou loops.
- Não faça uma pesquisa sequencial como um todo
JsonDocumentName
através de cada propriedade usandoRaizElemento
. Em vez disso, pesquise objetos JSON aninhados com base na estrutura conhecida dos dados JSON. Por exemplo, os exemplos de código anteriores procuram umNota
propriedade emEstudante
objetos percorrendo oEstudante
objetos e obter o valor deNota
para cada um, em vez de procurar em todosJsonElementName
objetos procurandoNota
propriedades. Fazer o último resultaria em passagens desnecessárias sobre os mesmos dados.
UsarJsonDocumentName
escrever JSON
O exemplo a seguir mostra como escrever JSON de umJsonDocumentName:
string jsonString = File.ReadAllText(inputFileName);var writerOptions = new JsonWriterOptions{ Indented = true};var documentOptions = new JsonDocumentOptions{ CommentHandling = JsonCommentHandling.Skip};usando FileStream fs = File.Create(outputFileName);usando var writer = novo Utf8JsonWriter(fs, opções: writerOptions);usando JsonDocument document = JsonDocument.Parse(jsonString, documentOptions);JsonElement root = document.RootElement;if (root.ValueKind == JsonValueKind.Object){ writer.WriteStartObject();}else{ return;}foreach (propriedade JsonProperty em root.EnumerateObject()){ property.WriteTo(writer);}writer.WriteEndObject();writer.Flush();
Dim jsonString As String = File.ReadAllText(inputFileName)Dim writerOptions As JsonWriterOptions = Novo JsonWriterOptions With { .Indented = True}Dim documentOptions As JsonDocumentOptions = Novo JsonDocumentOptions With { .CommentHandling = JsonCommentHandling.Skip}Dim fs As FileStream = File.Create( outputFileName)Dim writer As Utf8JsonWriter = New Utf8JsonWriter(fs, options:=writerOptions)Dim document As JsonDocument = JsonDocument.Parse(jsonString, documentOptions)Dim root As JsonElement = document.RootElementIf root.ValueKind = JsonValueKind.[Object] Then writer. WriteStartObject()Else ReturnEnd IfFor Each [property] As JsonProperty In root.EnumerateObject() [property].WriteTo(writer)Nextwriter.WriteEndObject()writer.Flush()
O código anterior:
- Lê um arquivo JSON, carrega os dados em um
JsonDocumentName
, e grava JSON formatado (impresso de forma bonita) em um arquivo. - UsosJsonDocumentOptionspara especificar que os comentários no JSON de entrada são permitidos, mas ignorados.
- Quando terminar, chamaRuborno escritor. Uma alternativa é permitir que o gravador faça a descarga automática quando for descartado.
Aqui está um exemplo de entrada JSON a ser processada pelo código de exemplo:
{"Class Name": "Science","Teacher's Name": "Jane","Semestre": "2019-01-01","Students": [{"Name": "John","Grade": 94,3 },{"Name": "James","Grade": 81,0},{"Name": "Julia","Grade": 91,9},{"Name": "Jessica","Grade": 72,4}, {"Nome": "Johnathan"}],"Final": verdadeiro}
O resultado é a seguinte saída JSON bem impressa:
{ "Class Name": "Science", "Teacher\u0027s Name": "Jane", "Semestre": "2019-01-01", "Students": [ { "Name": "John", "Grade" : 94,3 }, { "Nome": "James", "Grade": 81,0 }, { "Nome": "Julia", "Grade": 91,9 }, { "Nome": "Jessica", "Grade": 72,4 }, { "Nome": "Johnathan" } ], "Final": verdadeiro}
JsonDocument é IDisposable
JsonDocumentName
cria uma exibição na memória dos dados em um buffer agrupado. Portanto, oJsonDocumentName
tipo implementaIDisposable
e precisa ser usado dentro de umusando
bloquear.
Devolver apenas umJsonDocumentName
da sua API se quiser transferir a propriedade vitalícia e descartar a responsabilidade para o chamador. Na maioria dos cenários, isso não é necessário. Se o chamador precisar trabalhar com todo o documento JSON, retorne oClonedoRaizElemento, que é umJsonElementName. Se o chamador precisar trabalhar com um elemento específico no documento JSON, retorne oClonepor essaJsonElementName. Se você devolver oRaizElemento
ou um subelemento diretamente sem fazer umaClone
, o autor da chamada não poderá acessar o retornoJsonElementName
depois deJsonDocumentName
que o possui está disposto.
Aqui está um exemplo que requer que você faça umClone
:
public JsonElement LookAndLoad(JsonElement source){ string json = File.ReadAllText(source.GetProperty("fileName").GetString()); using (JsonDocument doc = JsonDocument.Parse(json)) { return doc.RootElement.Clone(); }}
O código anterior espera umJsonElementName
que contém umnome do arquivo
propriedade. Ele abre o arquivo JSON e cria umJsonDocumentName
. O método assume que o chamador deseja trabalhar com o documento inteiro, então ele retorna oClone
doRaizElemento
.
Se você receber umJsonElementName
e estão retornando um subelemento, não é necessário retornar umClone
do subelemento. O chamador é responsável por manter viva aJsonDocumentName
que o repassadoJsonElementName
pertence a. Por exemplo:
public JsonElement ReturnFileName(fonte JsonElement){ return source.GetProperty("fileName");}
JsonDocumentName
comJsonSerializerOptions
Você pode usarJsonSerializer
para serializar e desserializar uma instância deJsonDocumentName
. No entanto, a implementação para leitura e escritaJsonDocumentName
instâncias usandoJsonSerializer
é um invólucro sobre oJsonDocument.ParseValue(Utf8JsonReader)eJsonDocument.WriteTo(Utf8JsonWriter). Este wrapper não encaminha nenhumJsonSerializerOptions
(recursos do serializador) paraUtf8JsonReaderName
ouUtf8JsonWriterName
. Por exemplo, se você definirJsonSerializerOptions.DefaultIgnoreConditionparaWhenWritingNulle ligueJsonSerializer
com uma sobrecarga que levaJsonSerializerOptions
, as propriedades nulas não serão ignoradas.
O exemplo a seguir ilustra o resultado do uso de métodos que usam umJsonSerializerOptions
parâmetro e serializar umJsonDocumentName
instância:
usando System.Text;usando System.Text.Json;usando System.Text.Json.Nodes;usando System.Text.Json.Serialization;namespace JsonDocumentWithJsonSerializerOptions;public class Program{ public static void Main() { Person person = new Person { Nome = "Nancy" }; // Serialização padrão - Propriedade de endereço incluída no token nulo. // Output: {"Name":"Nancy","Address":null} string personJsonWithNull = JsonSerializer.Serialize(person); Console.WriteLine(pessoaJsonWithNull); // Serialize e ignore propriedades nulas - a propriedade de endereço nula é omitida // Saída: {"Name":"Nancy"} JsonSerializerOptions options = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; string pessoaJsonWithoutNull = JsonSerializer.Serialize(pessoa, opções); Console.WriteLine(pessoaJsonWithoutNull); // Ignorar propriedades nulas não funciona ao serializar a instância JsonDocument // usando JsonSerializer. // Output: {"Name":"Nancy","Address":null} var personJsonDocument = JsonSerializer.Deserialize(personJsonWithNull); personJsonWithNull = JsonSerializer.Serialize(personJsonDocument, opções); Console.WriteLine(pessoaJsonWithNull); }}public class Person{ public string? Nome { obter; definir; } string pública? Endereço { obter; definir; }}
Se você precisa de recursos deJsonSerializerOptions
, usarJsonSerializer
com alvos fortemente tipados (como oPessoa
classe neste exemplo) em vez deJsonDocumentName
.
Veja também
- Visão geral do System.Text.Json
- Referência da API System.Text.Json
- Referência da API System.Text.Json.Serialization
FAQs
How to install system text JSON serialization? ›
- Start a new project or open an existing project where this could be useful.
- Navigate to the Project menu.
- Select Manage NuGet Packages.
- Select Browse.
- Type System.Text.Json, as shown in Figure 1: Figure 1: System.Text.Json NuGet package.
- Click Install.
- using System;
- using Newtonsoft. Json;
- public class Example.
- {
- public static void Main()
- {
- string jsonString = "[{\"Name\":\"Chris\",\"Age\":25},{\"Name\":\"Jennifer\",\"Age\":20}]";
- dynamic customersList = JsonConvert. DeserializeObject(jsonString);
What is JSON? JSON (JavaScript Object Notation) is THE standard design for human-readable data interchange. It is a light-weight, human-readable format for storing and transporting data. Since JSON works with a tree structure, it looks like XML. Due to its built-in features, it is very easy to comprehend and use.
How to serialize an object to JSON in C#? ›Using Newtonsoft Json.NET to Serialize C# Objects
SerializeObject(obj); var jsonString = JsonConvert. SerializeObject(obj); Here, we turn an object into a JSON string by calling the SerializeObject() static method of the JsonConvert object.
- Extract JSON-2.90.tar.gz: tar -xvf JSON-2.90.tar.gz. This creates a directory called /JSON-2.90.
- Go to /JSON-2.90 and run the following commands to install the module: perl Makefile.PL make make test sudo make install.
- Go to Releases on the GitHub project page.
- Find the release you want to install.
- Download the release by clicking the release asset called marcusolsson-json-datasource-<version>. zip . ...
- Unarchive the plugin into the Grafana plugins directory. Linux. ...
- Restart the Grafana server to load the plugin.
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.
How to convert string to JSON format? ›- JSONParser parser = new JSONParser();
- JSONObject json = (JSONObject) parser.parse(stringToParse);
Read the contents of the file and deserialize it to a collection in C#, add the new record then serialise to JSON and overwrite the existing file. Here's some code to do what you need: var path = @"path_to_json_file"; var json = File. ReadAllText(path); var people = JsonConvert.
How to convert type object to string in C#? ›In C# object is the main class and it's also the parent or root of all the classes hence c# is the object-oriented language. We can convert the object to other data types like string, arrays, etc. Here we convert the object to a string by using the Object. toString() method for translating the object to string values.
How to store JSON data in text file C#? ›
First, we serialize the object to a string using JsonSerializer. Serialize method for the native version and JsonConvert. SerializeObject for Newtonsoft. Then, we write this string to file using File.
How to validate JSON with JSON schema in C#? ›The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
How to access data from JSON file in C#? ›First, we use a StreamReader object to read the contents of the JSON file into a string variable called json . Next, we invoke the JArray. Parse() method and pass the JSON string to it. This method parses the string into a JArray object, which is a collection of JToken objects representing the data in the JSON file.
How to bind JSON data to class in C#? ›- Step 1 : Copy the JSON body inside the first code editor. Make sure that the JSON string is well formatted. ...
- Step 2 : Click Convert in order to start generating C# classes. ...
- Step 3 : Copy the retuned C# classes from the second editor and deserialize using the 'Root' class.
- Log on to the first master node as a root or SUDO user.
- Create a file named config. json in a specified directory. For example, create /tmp/config. ...
- Open the file and enter the following text. You can also refer to some sample config. ...
- Save the config. json file.
- Read the JSON in Python dict or list object.
- Append the JSON to dict (or list ) object by modifying it.
- Write the updated dict (or list ) object into the original file.
To insert JSON data, add JSON to the INSERT command.. Note the absence of the keyword VALUES and the list of columns that is present in other INSERT commands. cqlsh> INSERT INTO cycling.
How to install JSON file in Windows? ›- Step 1: Verify your Java Installation. First of all, you need to have Java Software Development Kit (SDK) installed on your system. ...
- Step 2: Set your Java Environment. ...
- Step 3: Install Org. ...
- Step 4: Set JSON_JAVA Environment. ...
- Step 5: Set CLASSPATH Variable.
- run command npm init. it will take a while to process, click on yes. ...
- run command npm install --save json-server. ...
- run command in terminal touch database.json. ...
- go to package.json file. ...
- run command npm run start. ...
- go to postman.
- Notepad.
- Notepad++
- Microsoft Notepad.
- Microsoft WordPad.
- Mozilla Firefox.
- File Viewer Plus.
- Altova XMLSpy.
How to read data from JSON? ›
Example - Parsing JSON
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
- Choose JSON files from your device. At the top of this page, drag and drop your JSONs. ...
- Click or tap on TXT from the list of target formats. ...
- Download your TXT files, after MConverter has finished processing them.
- Load DOC file using Document class.
- Convert DOC to HTML by using Save method.
- Load HTML document by using Workbook class.
- Save the document to JSON format using Save method.
Formating data to JSON and making a POST request
fromEntries() method. Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back.
- Choose TXT files from your device. At the top of this page, drag and drop your TXTs. ...
- Click or tap on JSON from the list of target formats. ...
- Download your JSON files, after MConverter has finished processing them.
To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation.
How to create JSON from text? ›- Using Text Editor. Open a Text editor like Notepad, Visual Studio Code, Sublime, or your favorite one. ...
- Using Online Tool. Open a JSON Formatter tool from the link below. ...
- Create a file from the JSON URL. The developer needs to work with API; nowadays, 95% of API returns data as JSON.
- public class StringToObjectExample{
- public static void main(String args[]){
- String s="hello";
- Object obj=s;
- System.out.println(obj);
- }}
Formatting. You can format your JSON document using Ctrl+Shift+I or Format Document from the context menu.
How to handle JSON in C#? ›If you want to create or read a JSON string, you need a JSON Serialize or Deserialize. So, please open your Solution Explorer in Visual Studio, right click on References, and then click “Manage NuGet Packages”. Please search “Newtonsoft. JSON”on Nuget Package Manager and install it.
How to create a JSON object? ›
To create an object we need to use opening and closing curly braces {} and then inside of that we'll put all of the key value pairs that make up our object. Every single property inside the JSON is a key value pair. The key must be surrounded by double "" quotes followed by a colon : and then the value for that key.
How to add JSON object to JSON file? ›In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time.
How to convert datatype to string? ›If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.
How do you convert a string type? ›- Use Integer.parseInt() to Convert a String to an Integer. This method returns the string as a primitive type int. ...
- Use Integer.valueOf() to Convert a String to an Integer. This method returns the string as an integer object.
- class Emp{}
- public class ObjectToStringExample{
- public static void main(String args[]){
- Emp e=new Emp();
- String s=e.toString();
- String s2=String.valueOf(e);
- System.out.println(s);
- System.out.println(s2);
Once you have your JSON string ready, save it within a JSON file. For example, if you're using Windows, then you may copy the JSON string into Notepad. Then, save the notepad with your desired file name and add the . json extension at the end of the file name.
How to store JSON data in file? ›- Import json package. import json. import json.
- Write json data in hash format. Json_value ={ ...
- Create json file and use "w" (write) mode to save data and files. save_file = open("filename", "w") ...
- Use json. dump method to connect file and json data.
- Close the file.
LOB storage - JSON documents can be stored as-is in NVARCHAR columns. This is the best way for quick data load and ingestion because the loading speed matches the loading speed of string columns.
What tool to validate JSON? ›JSONLint is a validator and reformatter for JSON, a lightweight data-interchange format. Copy and paste, directly type, or input a URL in the editor above and let JSONLint tidy and validate your messy JSON code.
How to read JSON object value in C#? ›To get values from the JSON object, we pass the keys as indexes to the JObject, using the square bracket notation. After getting the values, we cast them to the desired type.
How to check the type of JSON object in C#? ›
In C# we can use typeof to determine the object type e.g. To achieve the same on a complex json object, I wrote this generic utility class in typescript to determine the instance type of the object.
How to get JSON data from a JSON file? ›Any JSON data can be consumed from different sources like a local JSON file by fetching the data using an API call. After getting a response from the server, you need to render its value. You can use local JSON files to do an app config, such as API URL management based on a server environment like dev, QA, or prod.
How to read JSON file from local path in C#? ›- using System. IO;
- using System. Text. Json;
-
- class ReadJsonFile.
- {
- static void Main()
- {
- string text = File. ReadAllText(@"./person.json");
To get JSON from a REST API endpoint using C#/. NET, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.
How to parse JSON object to class? ›It's pretty easy to parse JSON messages into a Java object using Jackson. You just need to use the ObjectMapper class, which provides the readValue() method. This method can convert JSON String to Java object, that's why it takes JSON as a parameter and the Class instance in which you want to parse your JSON.
How to convert JSON data to string in Java? ›toString() method is a useful method provided by the org. json package in Java that converts a JSON object to a string representation. This method is essential when transmitting JSON data over a network, storing it in a file, or displaying it on a web page.
How to send data in JSON format in Web API C#? ›To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You must also specify the data type using the Content-Type: application/json request header.
How to install Python JSON module? ›json is a built-in module in Python, you don't need to install it with pip. The json library can parse JSON from strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings.
How to install JSON file in vscode? ›To create a launch.json file, click the create a launch.json file link in the Run start view. If you go back to the File Explorer view (Ctrl+Shift+E), you'll see that VS Code has created a .vscode folder and added the launch.json file to your workspace.
How to install JSON server in Visual Studio Code? ›- run command npm init. it will take a while to process, click on yes. ...
- run command npm install --save json-server. ...
- run command in terminal touch database.json. ...
- go to package.json file. ...
- run command npm run start. ...
- go to postman.
How to install JSON extension in Visual Studio Code? ›
- Right click the References node in your Project and click Manage Nuget Packages...
- In the Nuget Package Manager Dialog box, make sure Online is selected in the left pane. Type Json.Net in the search box in the top right. ...
- Click the Install button.
Installing Python Packages with Setup.py
To install a package that includes a setup.py file, open a command or terminal window and: cd into the root directory where setup.py is located. Enter: python setup.py install.
- Import json package. import json. import json.
- Write json data in hash format. Json_value ={ "best_student": { ...
- Create json file and use "w" (write) mode to save data and files. save_file = open("filename", "w") ...
- Use json. dump method to connect file and json data.
- Close the file.
- Step 1: Download PIP get-pip.py. Before installing PIP, download the get-pip.py file. ...
- Step 2: Installing PIP on Windows. To install PIP type in the following: python get-pip.py. ...
- Step 3: Verify Installation. ...
- Step 4: Add Pip to Windows Environment Variables. ...
- Step 5: Configuration.
- Notepad.
- Notepad++
- Microsoft Notepad.
- Microsoft WordPad.
- Mozilla Firefox.
- File Viewer Plus.
- Altova XMLSpy.
You can open the settings.json file with the Preferences: Open Settings (JSON) command in the Command Palette (Ctrl+Shift+P). Once the file is open in an editor, delete everything between the two curly braces {} , save the file, and VS Code will go back to using the default values.
How to get json format in Visual Studio Code? ›Formatting. You can format your JSON document using Ctrl+Shift+I or Format Document from the context menu.
How to install json library in Java? ›- Step 1: Verify your Java Installation. First of all, you need to have Java Software Development Kit (SDK) installed on your system. ...
- Step 2: Set your Java Environment. ...
- Step 3: Install Org. ...
- Step 4: Set JSON_JAVA Environment. ...
- Step 5: Set CLASSPATH Variable.
- Step 1: To set up the JSON Server run the following command: npm install -g json-server.
- Step 2: Create a db.json file with some data. { “posts”: [ ...
- Step 3: Start JSON Server. json-server --watch db.json --port 8000. This runs a local server on port 8000, and watches the db.json file for any changes.
To put JSON data to the server, you need to make an HTTP PUT request to the server, specify the correct MIME data type for the JSON, and provide the JSON data in the body of the PUT message. The correct MIME type for JSON is application/json.
How do I manually install extensions in Visual Studio code? ›
You can browse and install extensions from within VS Code. Bring up the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of VS Code or the View: Extensions command (Ctrl+Shift+X). This will show you a list of the most popular VS Code extensions on the VS Code Marketplace.
How to install json net in Visual Studio? ›- Select Project > Manage NuGet Packages.
- In the NuGet Package Manager page, choose nuget.org as the Package source.
- From the Browse tab, search for Newtonsoft. Json, select Newtonsoft. ...
- If you're prompted to verify the installation, select OK.
- Open notepad++ -> ALT+P -> Plugin Manager -> Selcet JSON Viewer -> Click Install.
- Restart notepad++
- Now you can use shortcut to format json as CTRL + ALT +SHIFT + M or ALT+P -> Plugin Manager -> JSON Viewer -> Format JSON.