JSON
HashMap
Java
DataConversion
ProgrammingTutorial

Convert a JSON string to a HashMap in Java

Codemia Knowledge Hub ·

Use Jackson's ObjectMapper.readValue with a TypeReference<HashMap<String, Object>>, or Gson's fromJson with a TypeToken. The real decisions are which library fits your project and whether a dynamic map is the right shape at all, since typed classes are safer for business logic.

Converting with Jackson

Jackson handles dynamic JSON payloads well:

java
1import com.fasterxml.jackson.core.type.TypeReference;
2import com.fasterxml.jackson.databind.ObjectMapper;
3
4import java.util.HashMap;
5
6public class JsonToMapDemo {
7    public static void main(String[] args) throws Exception {
8        String json = "{\"name\":\"Ada\",\"age\":33,\"active\":true}";
9
10        ObjectMapper mapper = new ObjectMapper();
11        HashMap<String, Object> map = mapper.readValue(
12            json,
13            new TypeReference<HashMap<String, Object>>() {}
14        );
15
16        System.out.println(map);
17    }
18}

TypeReference is better than raw HashMap.class because it keeps the generic types and avoids unchecked warnings.

Converting with Gson

Gson does the same with a TypeToken:

java
1import com.google.gson.Gson;
2import com.google.gson.reflect.TypeToken;
3
4import java.lang.reflect.Type;
5import java.util.HashMap;
6
7public class GsonMapDemo {
8    public static void main(String[] args) {
9        String json = "{\"city\":\"Toronto\",\"population\":3000000}";
10        Gson gson = new Gson();
11
12        Type t = new TypeToken<HashMap<String, Object>>() {}.getType();
13        HashMap<String, Object> map = gson.fromJson(json, t);
14
15        System.out.println(map);
16    }
17}

Either library works. Go with your project's standard and existing dependencies.

Nested objects and arrays

Nested JSON objects become nested maps, and arrays become lists:

java
1String json = "{\"user\":{\"id\":7,\"name\":\"Lin\"},\"roles\":[\"admin\",\"editor\"]}";
2HashMap<String, Object> map = mapper.readValue(
3    json,
4    new TypeReference<HashMap<String, Object>>() {}
5);
6
7Object userObj = map.get("user");
8System.out.println(userObj.getClass());

Reading nested values means casting. That is flexible but less safe than typed DTOs. Do not assume a value is a particular numeric type without checking.

Handling invalid JSON

Do not swallow parse errors or return an empty map. Fail with a clear message:

java
1import com.fasterxml.jackson.core.JsonProcessingException;
2
3public static HashMap<String, Object> parseJsonToMap(String json, ObjectMapper mapper) {
4    try {
5        return mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {});
6    } catch (JsonProcessingException ex) {
7        throw new IllegalArgumentException("Invalid JSON payload", ex);
8    }
9}

In API services, combine this with input size limits and schema checks where needed.

When a typed class beats a HashMap

Dynamic maps suit exploratory or metadata-heavy payloads whose structure is unknown at compile time. For stable contracts, a typed class gives you:

  • compile-time type checks
  • clearer validation rules
  • easier refactoring
java
1class UserRequest {
2    public String name;
3    public int age;
4}
5
6UserRequest req = mapper.readValue(json, UserRequest.class);

Reading a few fields from large payloads

Converting a large payload into deeply nested maps can use a lot of memory. If you only need a few fields, use a streaming parser or Jackson's tree model instead:

java
var node = mapper.readTree(json);
String name = node.path("name").asText();

Limiting untrusted input

Unbounded JSON from external clients can become an attack surface when converted to dynamic maps. Constrain depth and size with:

  • request size limits at the API gateway
  • parser limits where supported
  • strict validation before storing map content

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms