how to identify a string for json

I have a string in json format.

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 in a line even. I would like to know how to identify this string to show in the identato format.

Author: Guilherme Nunes, 2018-05-24

3 answers

I don't think it's worth you trying to build a parser by yourself. There are many things to deal with and you have it ready.

You can create a method that uses the reader and writer from the library Newtonsoft and do the rewrite identified:

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 like this:

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

This example is available in dotnetfiddle.

I hope I helped.

 2
Author: Diego Rafael Souza, 2018-05-24 18:48:47

With the library JSON.NET you can create an instance of the Class JValue from the initial string and then show the representation of this object in string again using the 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 on .NET Fiddle

 2
Author: LINQ, 2018-05-24 18:03:02

You can use the library JSON.Net

Example of the site itself of what it would look like:

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 identify only the string you can use:

JsonConvert.SerializeObject(new { 'sua_string_aqui' });
 1
Author: Leticia Rosa, 2018-05-24 17:44:56