In this short article, you'll learn how to convert a JSON string to a Map
in Java and vice versa using the Jackson library.
Dependencies
To add Jackson to your Gradle project, add the following dependency to the build.gradle
file:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0'
For Maven, include the below dependency to your pom.xml
file:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</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 readValue()
method from ObjectMapper
:
try {
// JSON string
String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
"\"roles\":[\"Member\",\"Admin\"],\"admin\":true}";
// convert a JSON string to Java Map
Map<String, Object> map = new ObjectMapper().readValue(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 File
to readValue()
:
Map<String, Object> map = new ObjectMapper().readValue(
Paths.get("user.json").toFile(),
Map.class
);
Convert Map to JSON String
To convert a Java Map
to a JSON string, you can use the writeValueAsString()
method from the ObjectMapper
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 ObjectMapper().writeValueAsString(map);
// print JSON string
System.out.println(json);
} catch (Exception ex) {
ex.printStackTrace();
}
You should see the following JSON printed on the console:
{"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, use the writeValue()
method instead:
new ObjectMapper().writeValue(Paths.get("user.json").toFile(), map);
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.