In the following example you’ll see how to format JSON string using the Google Gson library. Here are the steps:
- We create a
Map
. - Put a couple key-value pairs to it. We put a string, a
LocalDate
object and an array ofString[]
. - Create a
Gson
object using theGsonBuilder
. This allows us to configure theGson
object. - We use the
setPrettyPrinting()
to configureGson
to output pretty print. - The
registerTypeAdapter()
allows us to register custom serializer, in this case we use it to serializeLocalDate
object.
Here is our code snippet:
package org.kodejava.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
public class GsonPrettyPrint {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "Duke");
map.put("address", "Menlo Park");
map.put("dateOfBirth", LocalDate.of(2000, Month.FEBRUARY, 1));
map.put("languages", new String[]{"Java", "Kotlin", "JavaScript"});
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
.create();
String json = gson.toJson(map);
System.out.println(json);
}
static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
@Override
public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_DATE));
}
}
}
Running this code produces the following result:
{
"address": "Menlo Park",
"languages": [
"Java",
"Kotlin",
"JavaScript"
],
"name": "Duke",
"dateOfBirth": "2000-02-01"
}
Maven Dependencies
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024