how to indent a string for json

3

I have a string in json format.

In this way:

{"IdLead":4186960,"Concessionaria":"Mila - Centro","DadosQualificacao":{"IdEvento":79654,"Qualificacao":1,"Motivo":6,"DescricaoMotivo":"motivo 1234","Ficha":["aaaaaaaa - TESTE","Ação desejada:=123456789 teste 132456789","Data Agendamento Test-Drive:=20/04/2018","Já é Cliente da Marca?=SIM"]},"DadosPessoa":{"Nome":"Guilherme Martins","Email":"[email protected]","DDD":11,"Telefone":948831041,"CpfCnpj":"44436740803","PreferenciaContato":0}}

I need to show this string on my screen, however, it appears on a line itself. I would like to know how to indent this string to show in identate format.

    
asked by anonymous 24.05.2018 / 19:29

3 answers

2

I think it's not worth your while trying to build a parser by itself. There are many things to deal with and you have it done.

You can create a method that uses the reader and writer of the Newtonsoft library and perform the indented rewrite:

public class JsonFormatting
{
    public static string Ident(string json)
    {
        using (var sr = new StringReader(json))
            using (var sw = new StringWriter())
            {
                var jr = new JsonTextReader(sr);
                var jw = new JsonTextWriter(sw) { Formatting = Formatting.Indented };
                jw.WriteToken(jr);
                return sw.ToString();
            }
    }
}

To use it, you will do so:

string json = "{ \"Id\":123456, \"Content\":\"Seu json vai aqui...\"}";
string formatted = JsonFormatting.Ident(json);

This example is available in dotnetfiddle.

I hope I have helped.

    
24.05.2018 / 20:03
2

With the JSON.NET library it is possible to create an instance of the class JValue from the initial string and then show the representation of this object in string again using formatting option that respects indentation.

For example:

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        var json = "{\"id\": 1, \"nome\": \"LINQ\"}";           
        var beauty = JValue.Parse(json).ToString(Formatting.Indented);
        Console.WriteLine(beauty);
    }
}

See working in .NET Fiddle

    
24.05.2018 / 20:03
1

You can use the JSON.Net library

Example of the site itself as it would be:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

To indent only the string you can use:

JsonConvert.SerializeObject(new { 'sua_string_aqui' });
    
24.05.2018 / 19:38