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?
NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method.
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.
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.
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).
You could use JSON.NET serializer, it supports JSON formatting
string body = JsonConvert.SerializeObject(message, Formatting.Indented);
Yon can download this package via NuGet.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With