In this short tutorial, you'll learn how to convert a JSON string to a Map
in Java and vice versa by using the Gson library.
Dependencies
To add Gson to your Gradle project, add the following dependency to build.gradle
file:
implementation 'com.google.code.gson:gson:2.8.6'
For Maven, include the below dependency to your pom.xml
file:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Convert JSON String to Map
To convert a JSON string to a Java Map
with the same properties and keys, you can use the fromJson()
method from Gson
:
try {
// JSON string
String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
"\"roles\":[\"Member\",\"Admin\"],\"admin\":true}";
// convert JSON string to Java Map
Map<String, Object> map = new Gson().fromJson(json, Map.class);
// print map keys and values
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
} catch (Exception ex) {
ex.printStackTrace();
}
You should see the following output printed on the console:
name=John Doe
email=john.doe@example.com
roles=[Member, Admin]
admin=true
To convert a JSON string stored in a file into a Java map, you can pass an instance of Reader
to fromJson()
, as shown below:
Map<String, Object> map = new Gson().fromJson(
new FileReader("user.json"),
Map.class);
Convert Map to JSON String
To convert a Java Map
to a JSON string, you can use the toJson()
method from the Gson
class:
try {
// create a map
Map<String, 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);
// convert map to JSON string
String json = new Gson().toJson(map);
// print JSON string
System.out.println(json);
} catch (Exception ex) {
ex.printStackTrace();
}
The above code will produce the following JSON:
{"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com"}
If you want to write the converted Map directly to a JSON file, just pass an instance of Writer
to the toJson()
method:
try {
// create a map
Map<String, 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 a writer
Writer writer = new FileWriter("user.json");
// convert map to JSON File
new Gson().toJson(map, writer);
// close the writer
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
For more Gson examples, check out the How to read and write JSON using Gson in Java tutorial.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.