JSON has become a famous data format for exchanging information over the Internet. It is commonly used in REST API and for storing loosely structured data. Compared to XML, it is concise, and unfortunately, less human readable. Beautifiers and pretty printers can easily enhance this. I will show you the different options available in GSON to convert an array of objects to a JSON string.
GSON default usage
To be able to use GSON, you need to add it to the project first. Here is a Maven dependency to add to pom.xml:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Probably the simplest way to convert an object to a JSON using GSON is by creating a Gson
object using GsonBuilder
and calling the toJson
method.
List<City> cities = new ArrayList<>();
cities.add(new City(1, "Rome"));
cities.add(new City(2, "Paris"));
cities.add(new City(3, "Madrid"));
Gson gson = new GsonBuilder()
.create();
System.out.println(gson.toJson(cities));
In this case, as in the whole article, I test it on a list of objects. The above code gives the following result:
[{"id":1,"name":"Rome"},{"id":2,"name":"Paris"},{"id":3,"name":"Madrid"}]
It is a valid JSON, it has all the necessary elements, and nothing is missing.
Array pretty printing
One may claim, that putting all array objects in a single line is not the best choice. It is correct for sure, and a computer will not complain, but if you want a human to read it, it could be more readable. It could be prettier, you might say. No problem! Let's configure GSON to generate pretty JSONs. It can be done by calling setPrettyPrinting()
on the GsonBuilder
.
List<City> cities = new ArrayList<>();
cities.add(new City(1, "Rome"));
cities.add(new City(2, "Paris"));
cities.add(new City(3, "Madrid"));
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
System.out.println(gson.toJson(cities));
The result is much more readable, isn't it?
[
{
"id": 1,
"name": "Rome"
},
{
"id": 2,
"name": "Paris"
},
{
"id": 3,
"name": "Madrid"
}
]
Each property has its own line. Intentions do their job as well.
Custom array pretty printing
That might seem weird, but none of those two ways of printing convinced me. The first one (one-liner) is a total mess if there are many objects. The second one looks good for three objects, but if you expect 100 of them, it will also become a mess.
Once, I had exactly these concerns and then, I wanted to have separate lines for each object. But a single object was simple enough to have all object properties in a single line. Unfortunately, GSON does not have a ready solution for that. You can read on their docs page:
The JsonFormatter is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default JsonPrintFormatter that has default line length of 80 character, 2 character indentation, and 4 character right margin.
So I had to do it manually. Here is my solution to print each object on a separate line.
List<City> cities = new ArrayList<>();
cities.add(new City(1, "Rome"));
cities.add(new City(2, "Paris"));
cities.add(new City(3, "Madrid"));
Gson gson = new GsonBuilder()
.create();
StringBuilder jsonArray = new StringBuilder("[\n");
for (City city : cities) {
jsonArray.append(gson.toJson(city)).append(",\n");
}
int lastIndex = jsonArray.length() - 1;
if (jsonArray.charAt(lastIndex) == ',') {
jsonArray.deleteCharAt(lastIndex);
}
jsonArray.append("]");
System.out.println(jsonArray);
Yes, there is much more code, because I had to iterate over the whole list and manually call toJson
on each object. But it works. Check the result:
[
{"id":1,"name":"Rome"},
{"id":2,"name":"Paris"},
{"id":3,"name":"Madrid"},
]
It looks nicer, isn't it?