Gson: Add custom indent for pretty printing

Created on 3 Apr 2018  路  5Comments  路  Source: google/gson

It would be great if we can specify custom indent while call pretty printing. Currently pretty printing always use 2 spaces for indent. This customization also allows to reduce size of resulting json.
Comparison table and code for generating json below:

| Indent \ setsCount | 100 | 2000 |
| --- | --- | --- |
| 2 spaces | 99,7 kb | 50,9 MB |
| 1 tab | 79,5 kb | 42,9 MB |
| nothing | 59,3 kb | 34,9 MB |

        List<Set<Integer>> sets = new ArrayList<Set<Integer>>();
        int setsCount = 2000;
        for (int setN = 0; setN < setsCount; setN++) {
            TreeSet<Integer> set = new TreeSet<Integer>();
            for (int i = 0; i < setsCount; i++) {
                set.add(setN * setsCount + i);
            }
            sets.add(set);
        }

        String json = gsonManager.getGson().toJson(sets);

Most helpful comment

My team's project stores some large configuration data in the git repository as JSON. If I don't use pretty option the resulting file contains a single line with the whole JSON, so git couldn't show a difference between different versions. Currently, I use pretty JSON, but in my case, it increases the size of the JSON from 30 - 40 MB up to 100+ MB. Bigger resulting JSON also requires more RAM for converting. So, I suppose it would be cool to have such feature as a custom indent.
And the other reason is that war between people using tabs and spaces is endless:) So, it is great to have both options.

All 5 comments

What's the motivation? If you care about size you aren't using pretty printing.

My team's project stores some large configuration data in the git repository as JSON. If I don't use pretty option the resulting file contains a single line with the whole JSON, so git couldn't show a difference between different versions. Currently, I use pretty JSON, but in my case, it increases the size of the JSON from 30 - 40 MB up to 100+ MB. Bigger resulting JSON also requires more RAM for converting. So, I suppose it would be cool to have such feature as a custom indent.
And the other reason is that war between people using tabs and spaces is endless:) So, it is great to have both options.

I agree, if you are appending to an existing Json with either 2, 4 spaces or tab indent, it would be nice to have such a feature. I'm actually suprised there isn't.

+1 for configurable indent size

@JakeWharton , my motivation is being able to compare jsons generated with gson against json files formatted in other tools, in my case IntelliJ Idea.

+1 for configurability!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GoogleCodeExporter picture GoogleCodeExporter  路  15Comments

RobMans426 picture RobMans426  路  20Comments

kdehairy picture kdehairy  路  43Comments

priyankajagtap18 picture priyankajagtap18  路  14Comments

LucianWang picture LucianWang  路  42Comments