Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize data into indented json [duplicate]

Tags:

json

c#

file

I am using this code to serialize the users into json text file.

if (File.Exists(path))
{
    using (var file = File.CreateText(path))
    {
        var serializer = new JsonSerializer();
        serializer.Serialize(file, this.users);
    }
}

This is the result that I get :

[output]

How can I get a result like this :

[pretty-print]

like image 616
Art Avatar asked May 13 '16 00:05

Art


People also ask

Can you serialize JSON?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.

What is serialization into 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).

Can JSON serialize a list?

Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.

How do you serialize a JSON list in Python?

Use json. dumps() to serialize a list into a JSON object. Use json. dumps(list) to serialize list into a JSON string.


1 Answers

Set the formatting on the serializer to Indented.

var serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, this.users);    
like image 92
Jonathon Chase Avatar answered Oct 06 '22 23:10

Jonathon Chase