Como usar um documento JSON em System.Text.Json (2023)

  • 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.Jsonfornece duas maneiras de criar um JSON DOM:

  • JsonDocumentNamefornece a capacidade de criar um DOM somente leitura usandoUtf8JsonReaderName. Os elementos JSON que compõem o payload podem ser acessados ​​por meio doJsonElementNametipo. OJsonElementNametype fornece enumeradores de matriz e objeto junto com APIs para converter texto JSON em tipos .NET comuns.JsonDocumentNameexpõ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 entreJsonDocumentNameeJsonNode:

  • OJsonNodeO DOM pode ser alterado depois de criado. OJsonDocumentNameDOM é imutável.
  • OJsonDocumentNameO 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 umAlunosmatriz que tem umNotapropriedade.
  • Atribui uma nota padrão de 70 para os alunos que não têm nota.
  • Obtém o número de alunos doContarpropriedade deJsonArray.

JsonNodecomJsonSerializerOptions

Você pode usarJsonSerializerpara 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 ligueJsonSerializercom uma sobrecarga que levaJsonSerializerOptions, as propriedades nulas não serão ignoradas.

(Video) Como pegar os dados de um arquivo JSON usando JAVASCRIPT - Acessando um JSON com JAVASCRIPT

A mesma limitação se aplica aoJsonNodemétodos que levam umJsonSerializerOptionsparâmetro:WriteTo(Utf8JsonWriter, JsonSerializerOptions)eToJsonString(JsonSerializerOptions). Essas APIs usamJsonSerializerOptionsapenas para obter conversores personalizados.

O exemplo a seguir ilustra o resultado do uso de métodos que usam umJsonSerializerOptionsparâmetro e serializar umJsonNodeinstâ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 deJsonSerializerOptionsexceto conversores personalizados, useJsonSerializercom alvos fortemente tipados (como oPessoaclasse 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 chamadajsonString.
  • Calcula uma nota média para objetos em umAlunosmatriz que tem umNotapropriedade.
  • Atribui uma nota padrão de 70 para os alunos que não têm nota.
  • Cria oJsonDocumentNameinstância em umusando declaraçãoporqueJsonDocumentNameimplementosIDisposable. Após umJsonDocumentNameinstância é descartada, você perde o acesso a todos os seusJsonElementNameinstâncias também. Para manter o acesso a umJsonElementNameexemplo, faça uma cópia antes que o paiJsonDocumentNameinstâ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 umcontarvariá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:

(Video) Read/Write JSON Files with Node.js

{ "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 usaJsonNodeem vez deJsonDocumentName, verExemplo de nota média JsonNode.

Como pesquisar um JsonDocument e JsonElement para subelementos

Pesquisas emJsonElementNameexigem 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 umJsonDocumentNameobjeto:

  • 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 todoJsonDocumentNameatravé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 umNotapropriedade emEstudanteobjetos percorrendo oEstudanteobjetos e obter o valor deNotapara cada um, em vez de procurar em todosJsonElementNameobjetos procurandoNotapropriedades. Fazer o último resultaria em passagens desnecessárias sobre os mesmos dados.

UsarJsonDocumentNameescrever 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 umJsonDocumentName, 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

JsonDocumentNamecria uma exibição na memória dos dados em um buffer agrupado. Portanto, oJsonDocumentNametipo implementaIDisposablee precisa ser usado dentro de umusandobloquear.

(Video) How to read a Json file in C# and write a text file using C# and Newtonsoft.Json

Devolver apenas umJsonDocumentNameda 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 oRaizElementoou um subelemento diretamente sem fazer umaClone, o autor da chamada não poderá acessar o retornoJsonElementNamedepois deJsonDocumentNameque 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 umJsonElementNameque contém umnome do arquivopropriedade. 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 oClonedoRaizElemento.

Se você receber umJsonElementNamee estão retornando um subelemento, não é necessário retornar umClonedo subelemento. O chamador é responsável por manter viva aJsonDocumentNameque o repassadoJsonElementNamepertence a. Por exemplo:

public JsonElement ReturnFileName(fonte JsonElement){ return source.GetProperty("fileName");}

JsonDocumentNamecomJsonSerializerOptions

Você pode usarJsonSerializerpara serializar e desserializar uma instância deJsonDocumentName. No entanto, a implementação para leitura e escritaJsonDocumentNameinstâncias usandoJsonSerializeré um invólucro sobre oJsonDocument.ParseValue(Utf8JsonReader)eJsonDocument.WriteTo(Utf8JsonWriter). Este wrapper não encaminha nenhumJsonSerializerOptions(recursos do serializador) paraUtf8JsonReaderNameouUtf8JsonWriterName. Por exemplo, se você definirJsonSerializerOptions.DefaultIgnoreConditionparaWhenWritingNulle ligueJsonSerializercom 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 umJsonSerializerOptionsparâmetro e serializar umJsonDocumentNameinstâ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, usarJsonSerializercom alvos fortemente tipados (como oPessoaclasse neste exemplo) em vez deJsonDocumentName.

(Video) Como leer y escribir archivos JSON en C# con JSON.Net

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? ›

Installing System. Text. Json
  1. Start a new project or open an existing project where this could be useful.
  2. Navigate to the Project menu.
  3. Select Manage NuGet Packages.
  4. Select Browse.
  5. Type System.Text.Json, as shown in Figure 1: Figure 1: System.Text.Json NuGet package.
  6. Click Install.
Aug 8, 2019

How to convert string to JSON in C#? ›

  1. using System;
  2. using Newtonsoft. Json;
  3. public class Example.
  4. {
  5. public static void Main()
  6. {
  7. string jsonString = "[{\"Name\":\"Chris\",\"Age\":25},{\"Name\":\"Jennifer\",\"Age\":20}]";
  8. dynamic customersList = JsonConvert. DeserializeObject(jsonString);

What is a JSON document C#? ›

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.

How to install the JSON module? ›

  1. Extract JSON-2.90.tar.gz: tar -xvf JSON-2.90.tar.gz. This creates a directory called /JSON-2.90.
  2. Go to /JSON-2.90 and run the following commands to install the module: perl Makefile.PL make make test sudo make install.

How to install JSON plugins? ›

Install manually
  1. Go to Releases on the GitHub project page.
  2. Find the release you want to install.
  3. Download the release by clicking the release asset called marcusolsson-json-datasource-<version>. zip . ...
  4. Unarchive the plugin into the Grafana plugins directory. Linux. ...
  5. Restart the Grafana server to load the plugin.

How to convert JSON document to string? ›

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? ›

We use the following statements to convert the JSON String to JSON Object.
  1. JSONParser parser = new JSONParser();
  2. JSONObject json = (JSONObject) parser.parse(stringToParse);

How to insert JSON file in C#? ›

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#? ›

  1. Step 1 : Copy the JSON body inside the first code editor. Make sure that the JSON string is well formatted. ...
  2. Step 2 : Click Convert in order to start generating C# classes. ...
  3. Step 3 : Copy the retuned C# classes from the second editor and deserialize using the 'Root' class.

How to setup JSON files? ›

json file, follow these steps:
  1. Log on to the first master node as a root or SUDO user.
  2. Create a file named config. json in a specified directory. For example, create /tmp/config. ...
  3. Open the file and enter the following text. You can also refer to some sample config. ...
  4. Save the config. json file.
Oct 6, 2020

How to add JSON in file? ›

In Python, appending JSON to a file consists of the following steps:
  1. Read the JSON in Python dict or list object.
  2. Append the JSON to dict (or list ) object by modifying it.
  3. Write the updated dict (or list ) object into the original file.
Dec 9, 2022

How to insert in JSON format? ›

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? ›

Org. Json - Environment Setup
  1. Step 1: Verify your Java Installation. First of all, you need to have Java Software Development Kit (SDK) installed on your system. ...
  2. Step 2: Set your Java Environment. ...
  3. Step 3: Install Org. ...
  4. Step 4: Set JSON_JAVA Environment. ...
  5. Step 5: Set CLASSPATH Variable.

How to install JSON-server locally? ›

now, open terminal in vs-code.
  1. run command npm init. it will take a while to process, click on yes. ...
  2. run command npm install --save json-server. ...
  3. run command in terminal touch database.json. ...
  4. go to package.json file. ...
  5. run command npm run start. ...
  6. go to postman.
Jul 3, 2022

How to open JSON file? ›

Windows tools to open JSON file
  1. Notepad.
  2. Notepad++
  3. Microsoft Notepad.
  4. Microsoft WordPad.
  5. Mozilla Firefox.
  6. File Viewer Plus.
  7. 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.

How to convert JSON file to readable text? ›

You can convert JSON to TXT with MConverter in three easy steps:
  1. Choose JSON files from your device. At the top of this page, drag and drop your JSONs. ...
  2. Click or tap on TXT from the list of target formats. ...
  3. Download your TXT files, after MConverter has finished processing them.

How to convert a document to JSON? ›

How to Convert DOC to JSON via Java?
  1. Load DOC file using Document class.
  2. Convert DOC to HTML by using Save method.
  3. Load HTML document by using Workbook class.
  4. Save the document to JSON format using Save method.

How to format data in JSON format? ›

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.

How to convert to JSON format in notepad? ›

How to convert TXT to JSON?
  1. Choose TXT files from your device. At the top of this page, drag and drop your TXTs. ...
  2. Click or tap on JSON from the list of target formats. ...
  3. Download your JSON files, after MConverter has finished processing them.

How to extract data from JSON format? ›

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? ›

How to Create JSON File?
  1. Using Text Editor. Open a Text editor like Notepad, Visual Studio Code, Sublime, or your favorite one. ...
  2. Using Online Tool. Open a JSON Formatter tool from the link below. ...
  3. Create a file from the JSON URL. The developer needs to work with API; nowadays, 95% of API returns data as JSON.
Jun 21, 2020

How to convert string into object? ›

Java String to Object Example
  1. public class StringToObjectExample{
  2. public static void main(String args[]){
  3. String s="hello";
  4. Object obj=s;
  5. System.out.println(obj);
  6. }}

How to format JSON string in visual code? ›

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? ›

Java String to Int – How to Convert a String to an Integer
  1. Use Integer.parseInt() to Convert a String to an Integer. This method returns the string as a primitive type int. ...
  2. Use Integer.valueOf() to Convert a String to an Integer. This method returns the string as an integer object.
Nov 23, 2020

How to convert class type into string? ›

Java Object to String Example: Converting User-defined class
  1. class Emp{}
  2. public class ObjectToStringExample{
  3. public static void main(String args[]){
  4. Emp e=new Emp();
  5. String s=e.toString();
  6. String s2=String.valueOf(e);
  7. System.out.println(s);
  8. System.out.println(s2);

Can I save a JSON in a text file? ›

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? ›

There are the following steps to create and save json files:
  1. Import json package. import json. import json.
  2. Write json data in hash format. Json_value ={ ...
  3. Create json file and use "w" (write) mode to save data and files. save_file = open("filename", "w") ...
  4. Use json. dump method to connect file and json data.
  5. Close the file.

What is the best way to store JSON documents? ›

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#? ›

Read the JSON file and create the C# object
  1. using System. IO;
  2. using System. Text. Json;
  3. class ReadJsonFile.
  4. {
  5. static void Main()
  6. {
  7. string text = File. ReadAllText(@"./person.json");

How to get JSON data from REST API in C#? ›

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? ›

now, open terminal in vs-code.
  1. run command npm init. it will take a while to process, click on yes. ...
  2. run command npm install --save json-server. ...
  3. run command in terminal touch database.json. ...
  4. go to package.json file. ...
  5. run command npm run start. ...
  6. go to postman.
Jul 3, 2022

How to install JSON extension in Visual Studio Code? ›

Install Json.Net using the Visual Studio Solution Explorer. #
  1. Right click the References node in your Project and click Manage Nuget Packages...
  2. 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. ...
  3. Click the Install button.

How to install Python module from file? ›

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.

How to download JSON in Python? ›

Steps to save the json file
  1. Import json package. import json. import json.
  2. Write json data in hash format. Json_value ={ "best_student": { ...
  3. Create json file and use "w" (write) mode to save data and files. save_file = open("filename", "w") ...
  4. Use json. dump method to connect file and json data.
  5. Close the file.

How to install pip in Python? ›

Installing PIP On Windows
  1. Step 1: Download PIP get-pip.py. Before installing PIP, download the get-pip.py file. ...
  2. Step 2: Installing PIP on Windows. To install PIP type in the following: python get-pip.py. ...
  3. Step 3: Verify Installation. ...
  4. Step 4: Add Pip to Windows Environment Variables. ...
  5. Step 5: Configuration.
Feb 19, 2019

How do I run a json file? ›

Below is a list of tools that can open a JSON file on the Windows platform:
  1. Notepad.
  2. Notepad++
  3. Microsoft Notepad.
  4. Microsoft WordPad.
  5. Mozilla Firefox.
  6. File Viewer Plus.
  7. Altova XMLSpy.

How to open json file in visual code? ›

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? ›

org. json - Environment Setup
  1. Step 1: Verify your Java Installation. First of all, you need to have Java Software Development Kit (SDK) installed on your system. ...
  2. Step 2: Set your Java Environment. ...
  3. Step 3: Install Org. ...
  4. Step 4: Set JSON_JAVA Environment. ...
  5. Step 5: Set CLASSPATH Variable.

How to install json server in CMD? ›

Introducing JSON Server
  1. Step 1: To set up the JSON Server run the following command: npm install -g json-server.
  2. Step 2: Create a db.json file with some data. { “posts”: [ ...
  3. 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.
Sep 21, 2018

How to put json on server? ›

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? ›

Json package in Visual Studio, follow these steps:
  1. Select Project > Manage NuGet Packages.
  2. In the NuGet Package Manager page, choose nuget.org as the Package source.
  3. From the Browse tab, search for Newtonsoft. Json, select Newtonsoft. ...
  4. If you're prompted to verify the installation, select OK.
Feb 21, 2023

How to install json plugin in Notepad ++ manually? ›

To install the plugin do the following steps:
  1. Open notepad++ -> ALT+P -> Plugin Manager -> Selcet JSON Viewer -> Click Install.
  2. Restart notepad++
  3. Now you can use shortcut to format json as CTRL + ALT +SHIFT + M or ALT+P -> Plugin Manager -> JSON Viewer -> Format JSON.

Videos

1. Newtonsoft Json vs System.Text.Json
(devsdna)
2. Fetch Data from JSON File in React JS | React JSON [ UPDATED ]
(WebStylePress)
3. How To Read a JSON File With JavaScript
(codebubb)
4. How to Parse JSON in C
(Hathibelagal Productions)
5. Appsettings.json in .NET: How to read and get a value
(Round The Code)
6. Fetch and Display Advanced JSON Data in Chart JS
(Chart JS)

References

Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated: 06/23/2023

Views: 5553

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.