2011-05-04 9 views

Respuesta

10

Parece ser que no hay una herramienta incorporada para formatear la salida del serializador JSON.
Supongo que la razón por la que esto sucedió es la minimización de los datos que enviamos a través de la red.

¿Está seguro de que necesita datos formateados en el código? ¿O desea analizar JSON solo durante la depuración?

Hay una gran cantidad de servicios en línea que ofrecen dicha funcionalidad: 1, 2. O aplicación independiente: JSON viewer.

Pero si necesita formatear dentro de la aplicación, puede escribir appropriate code usted mismo.

31

Usted podría utilizar JSON.NET serializador, es compatible con el formato JSON

string body = JsonConvert.SerializeObject(message, Formatting.Indented); 

Yon puede descargar a través de this package NuGet.

+0

Incluso puede configurar la configuración de formato deseada JsonConvert.SerializeObject (mensaje, Newtonsoft.Json.Formatting.Indented, nueva JsonSerializerSettings {ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()}); –

16

Aquí está mi solución que no requiere el uso de JSON.NET y es más simple que el código vinculado por Alex Zhevzhik.

using System.Web.Script.Serialization; 
    // add a reference to System.Web.Extensions 


    public void WriteToFile(string path) 
    { 
     var serializer  = new JavaScriptSerializer(); 
     string json  = serializer.Serialize(this); 
     string json_pretty = JSON_PrettyPrinter.Process(json); 
     File.WriteAllText(path, json_pretty); 
    } 

y aquí está el formateador

class JSON_PrettyPrinter 
{ 
    public static string Process(string inputText) 
    { 
     bool escaped = false; 
     bool inquotes = false; 
     int column = 0; 
     int indentation = 0; 
     Stack<int> indentations = new Stack<int>(); 
     int TABBING = 8; 
     StringBuilder sb = new StringBuilder(); 
     foreach (char x in inputText) 
     { 
      sb.Append(x); 
      column++; 
      if (escaped) 
      { 
       escaped = false; 
      } 
      else 
      { 
       if (x == '\\') 
       { 
        escaped = true; 
       } 
       else if (x == '\"') 
       { 
        inquotes = !inquotes; 
       } 
       else if (!inquotes) 
       { 
        if (x == ',') 
        { 
         // if we see a comma, go to next line, and indent to the same depth 
         sb.Append("\r\n"); 
         column = 0; 
         for (int i = 0; i < indentation; i++) 
         { 
          sb.Append(" "); 
          column++; 
         } 
        } else if (x == '[' || x== '{') { 
         // if we open a bracket or brace, indent further (push on stack) 
         indentations.Push(indentation); 
         indentation = column; 
        } 
        else if (x == ']' || x == '}') 
        { 
         // if we close a bracket or brace, undo one level of indent (pop) 
         indentation = indentations.Pop(); 
        } 
        else if (x == ':') 
        { 
         // if we see a colon, add spaces until we get to the next 
         // tab stop, but without using tab characters! 
         while ((column % TABBING) != 0) 
         { 
          sb.Append(' '); 
          column++; 
         } 
        } 
       } 
      } 
     } 
     return sb.ToString(); 
    } 

} 
+0

¿Por qué usar 'IDisposable'? ¿Por qué no simplemente hacer 'Process' un método estático? – tenfour

+0

@tenfour: tiene toda la razón. Este fragmento de código proviene de un bloque más grande que se simplificó para stackoverflow ... Lo simplificaré aún más. –

+0

¡No es una solución para todos! ¡Tendría conflictos de imagen de página (o formato) si su proyecto es un .NET 4 o si su proyecto no es una designación web! Observe que está utilizando System.Web.Extensions (¡necesita .NET4.5!) Para traer System.Web.Script.Serialization !! Para una solución concreta, debe usar NuGet para adquirir Newtonsoft y usar JsonConvert.SerializeObject –

5

también quería ser capaz de tener el formato JSON sin depender de un componente de terceros. La solución de Mark Lakata funcionó bien (gracias a Mark), pero quería que los corchetes y las tabulaciones fueran como los del enlace de Alex Zhevzhik. Así que aquí está una versión modificada del código de Mark que funciona de esa manera, en caso de que alguien más lo quiere:

/// <summary> 
/// Adds indentation and line breaks to output of JavaScriptSerializer 
/// </summary> 
public static string FormatOutput(string jsonString) 
{ 
    var stringBuilder = new StringBuilder(); 

    bool escaping = false; 
    bool inQuotes = false; 
    int indentation = 0; 

    foreach (char character in jsonString) 
    { 
     if (escaping) 
     { 
      escaping = false; 
      stringBuilder.Append(character); 
     } 
     else 
     { 
      if (character == '\\') 
      { 
       escaping = true; 
       stringBuilder.Append(character); 
      } 
      else if (character == '\"') 
      { 
       inQuotes = !inQuotes; 
       stringBuilder.Append(character); 
      } 
      else if (!inQuotes) 
      { 
       if (character == ',') 
       { 
        stringBuilder.Append(character); 
        stringBuilder.Append("\r\n"); 
        stringBuilder.Append('\t', indentation); 
       } 
       else if (character == '[' || character == '{') 
       { 
        stringBuilder.Append(character); 
        stringBuilder.Append("\r\n"); 
        stringBuilder.Append('\t', ++indentation); 
       } 
       else if (character == ']' || character == '}') 
       { 
        stringBuilder.Append("\r\n"); 
        stringBuilder.Append('\t', --indentation); 
        stringBuilder.Append(character); 
       } 
       else if (character == ':') 
       { 
        stringBuilder.Append(character); 
        stringBuilder.Append('\t'); 
       } 
       else 
       { 
        stringBuilder.Append(character); 
       } 
      } 
      else 
      { 
       stringBuilder.Append(character); 
      } 
     } 
    } 

    return stringBuilder.ToString(); 
} 
Cuestiones relacionadas