Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set formatting with JavaScriptSerializer when JSON serializing?

I am using JavaScriptSerializer for serializing objects to the file to the JSON format. But the result file has no readable formatting. How can I allow formating to get a readable file?

like image 716
Peter17 Avatar asked May 04 '11 09:05

Peter17


People also ask

How to serialize JSON object in c#?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method.

What is Newtonsoft JSON formatting indented?

Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json. None − No special formatting is applied. This is the default. Indented − Causes child objects to be indented according to the Newtonsoft.

How does JSON deserialize work c#?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

What is serialize and deserialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


2 Answers

You could use JSON.NET serializer, it supports JSON formatting

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

Yon can download this package via NuGet.

like image 200
xelibrion Avatar answered Oct 03 '22 09:10

xelibrion


Here's my solution that does not require using JSON.NET and is simpler than the code linked by 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 );     } 

and here is the formatter

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();     }  } 
like image 24
Mark Lakata Avatar answered Oct 03 '22 11:10

Mark Lakata