How to read and write JSON using Gson in Java
In my previous article, we looked at reading and writing JSON files in Java using different open-source libraries like JSON.simple, Jackson, Moshi, and Gson.
In this article, you’ll learn how to read and write JSON using Gson in detail. Gson is a popular Java library developed and maintained by Google to convert Java Objects into their JSON representation.
It can also convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects, including pre-existing objects you do not modify.
implementation 'com.google.code.gson:gson:2.8.6'
dependency> groupId>com.google.code.gsongroupId> artifactId>gsonartifactId> version>2.8.6version> dependency>
public class Book private String title; private String isbn; private long year; private String[] authors; public Book() > public Book(String title, String isbn, long year, String[] authors) this.title = title; this.isbn = isbn; this.year = year; this.authors = authors; > // getters and setters, equals(), toString() . (omitted for brevity) >
To convert a Java Object to a JSON string, all you need to do is create a new instance of Gson and then call the toJson() method with Java Object as a parameter:
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // convert book object to JSON String json = new Gson().toJson(book); // print JSON string System.out.println(json); > catch (Exception ex) ex.printStackTrace(); >
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>
The toJson() method also accepts an instance of Writer as a second parameter that you can use to output the JSON directly to a file, as shown below:
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(book, writer); // close writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>
You can also convert a list of Java Objects to a JSON array using the same toJson() method, as shown below:
try // create books list ListBook> books = Arrays.asList( new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">), new Book("Head First Java", "0596009208", 2003, new String[]"Kathy Sierra", "Bert Bates">) ); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("books.json")); // convert books object to JSON file gson.toJson(books, writer); // close writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
["title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>, "title":"Head First Java","isbn":"0596009208","year":2003,"authors":["Kathy Sierra","Bert Bates"]>]
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create a Gson instance with pretty-printing Gson gson = new GsonBuilder().setPrettyPrinting().create(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(book, writer); // close writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
"title": "Thinking in Java", "isbn": "978-0131872486", "year": 1998, "authors": [ "Bruce Eckel" ] >
try // create a book map MapString, Object> map = new HashMap>(); map.put("title", "Thinking in Java"); map.put("isbn", "978-0131872486"); map.put("year", 1998); map.put("authors", new String[]"Bruce Eckel">); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(map, writer); // close writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
To convert a JSON string back to an equivalent Java Object, you can use the fromJson() method from Gson :
try // JSON string String json = " + ",\"year\":1998,\"authors\":[\"Bruce Eckel\"]>"; // create Gson instance Gson gson = new Gson(); // convert a JSON string to a Book object Book book = gson.fromJson(json, Book.class); // print book System.out.println(book); > catch (Exception ex) ex.printStackTrace(); >
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]>
The fromJson() method also accepts an instance of Reader to read and parse the JSON data from a file:
try // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // convert a JSON string to a Book object Book book = gson.fromJson(reader, Book.class); // print book System.out.println(book); // close reader reader.close(); > catch (Exception ex) ex.printStackTrace(); >
The following example shows how to convert a JSON array to a list of Java Objects using the Gson library:
try // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("books.json")); // convert JSON array to list of books ListBook> books = Arrays.asList(gson.fromJson(reader, Book[].class)); // print books books.forEach(System.out::println); // close reader reader.close(); > catch (Exception ex) ex.printStackTrace(); >
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> Booktitle='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]>
By using Gson, you can also convert a JSON file to a Java Map with the same properties and keys, as shown below:
try // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // convert JSON file to map Map?, ?> map = gson.fromJson(reader, Map.class); // print map entries for (Map.Entry?, ?> entry : map.entrySet()) System.out.println(entry.getKey() + "=" + entry.getValue()); > // close reader reader.close(); > catch (Exception ex) ex.printStackTrace(); >
year=1998.0 isbn=978-0131872486 title=Thinking in Java authors=[Bruce Eckel]
By default, Gson uses the class field names as JSON property names. With @SerializedName , you can specify a custom JSON property name:
public class Book @SerializedName("book_name") private String title; private String isbn; private long year; private String[] authors; // . >
"book_name":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>
By default, Gson ignores null fields while serializing a Java Object to its JSON representation:
try // create book object Book book = new Book("Thinking in Java", null, 1998, null); // create Gson instance Gson gson = new Gson(); // convert book object to JSON String json = gson.toJson(book); // print JSON string System.out.println(json); > catch (Exception ex) ex.printStackTrace(); >
"title":"Thinking in Java","year":1998>
To explicitly include the null fields in the final JSON output, you can use the serializeNulls() method from GsonBuilder :
Gson gson = new GsonBuilder().serializeNulls().create();
"title":"Thinking in Java","isbn":null,"year":1998,"authors":null>
Gson provides multiple ways to exclude fields while serializing or deserializing JSON. By default, all static and transient fields are excluded. However, you can change this default behavior with the excludeFieldsWithModifiers() method. For example, the following configuration excludes static fields only:
Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create();
If you want to exclude both static and transient , use the following (which is equivalent to the default configuration):
Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT) .create();
If you want to exclude fields explicitly, use the @Expose annotation. It defines the attributes to be excluded from serialization and deserialization to JSON. To enable @Expose , you need to create the Gson object like the below:
Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create();
public class Book @Expose(serialize = true, deserialize = true) private String title; @Expose private String isbn; @Expose(serialize = false, deserialize = true) private long year; private String[] authors; // . >
"title":"Thinking in Java","isbn":"978-0131872486">
You might also like.
How to write JSON to a file using Jackson
In this quick tutorial, you’ll learn how to write JSON data to a file by using the Jackson API. Jackson is a popular JSON processing library for reading, writing, and parsing JSON data in Java.
implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0'
dependency> groupId>com.fasterxml.jackson.coregroupId> artifactId>jackson-databindartifactId> version>2.10.0version> dependency>
To write a Java Map to a JSON file, you can use the writeValue() method from ObjectMapper as shown below:
try // create a map MapString, Object> map = new HashMap>(); map.put("name", "John Deo"); map.put("email", "john.doe@example.com"); map.put("roles", new String[]"Member", "Admin">); map.put("admin", true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert map to JSON file mapper.writeValue(Paths.get("user.json").toFile(), map); > catch (Exception ex) ex.printStackTrace(); >
"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com">
Let us first create a simple Java class named Book.java that we will use to convert a Java Object to a JSON file: Book.java
public class Book private String title; private String isbn; private long year; private String[] authors; public Book() > public Book(String title, String isbn, long year, String[] authors) this.title = title; this.isbn = isbn; this.year = year; this.authors = authors; > // getters and setters, equals(), toString() . (omitted for brevity) >
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert book object to JSON file mapper.writeValue(Paths.get("book.json").toFile(), book); > catch (Exception ex) ex.printStackTrace(); >
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>
Just like a single Java Object, you can also write a list of Java Objects to a JSON file using the same writeValue() method:
try // create a books list ListBook> books = Arrays.asList( new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">), new Book("Head First Java", "0596009208", 2003, new String[]"Kathy Sierra", "Bert Bates">) ); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert book object to JSON file mapper.writeValue(Paths.get("books.json").toFile(), books); > catch (Exception ex) ex.printStackTrace(); >
["title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>, "title":"Head First Java","isbn":"0596009208","year":2003,"authors":["Kathy Sierra","Bert Bates"]>]
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // create an instance of DefaultPrettyPrinter ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); // convert book object to JSON file writer.writeValue(Paths.get("book.json").toFile(), book); > catch (Exception ex) ex.printStackTrace(); >
"title" : "Thinking in Java", "isbn" : "978-0131872486", "year" : 1998, "authors" : [ "Bruce Eckel" ] >
For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.