0

Here is my example:

public class Obj {
    String field1;
    int field2;
    public Obj(String field1, int field2) {
        this.field1 = field1;
        this.field2 = field2;
    }   
    public static void main(String[] args) 
    {       
        final Obj o1 = new Obj("string1",1);
        final Obj o2 = new Obj("string2",2);

        List<Obj> list = new ArrayList<Obj>(){{
            add(o1);
            add(o2);
        }};

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonElement element = gson.toJsonTree(list, new TypeToken<List<Obj>>(){}.getType());
        JsonArray jsonArray = element.getAsJsonArray();
        System.out.println("1-");
        System.out.println(jsonArray.toString());        

        String json = gson.toJson(o1);
        System.out.println("2-");
        System.out.println(json);
    }
}

The output:

1-
[{"field1":"string1","field2":1},{"field1":"string2","field2":2}]

2-
{
  "field1": "string1",
  "field2": 1
}

How can I enable pretty printing for jsonArray?

I think this is enough to explain my problem, however here is some bla bla bla bla because stackoverflow ask me more details to let me post the question.

Alvins
  • 867
  • 16
  • 27

4 Answers4

2

toString(2) respect identation spaces

System.out.println(json.toString(2));
rafaelasguerra
  • 2,685
  • 5
  • 24
  • 56
2

It seems that JsonArray::toString doesn't provide a way to configure pretty-printing.

You may just have to deserialise it using your Gson instance:

System.out.println("3-");
System.out.println(gson.toJson(jsonArray));
Jonathan
  • 20,053
  • 6
  • 63
  • 70
0

You could use Jackson library.

Check this post: Convert JSON String to Pretty Print JSON output using Jackson

The question was really similar.

Community
  • 1
  • 1
Salec
  • 19
  • 5
0

If you have server on your project i suggest make simple index.jsp and out.println this JSON. And add this plugin to your Google Chrome JSON Viewer

You get pretty Print Json.

hurricane
  • 6,521
  • 2
  • 34
  • 44