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.
toString(2)尊重标识空间
System.out.println(json.toString(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));
You could use Jackson library.
Check this post: Convert JSON String to Pretty Print JSON output using Jackson
The question was really similar.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.