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:
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:
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:
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:
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
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:
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
Related reading
- Convert a list into a comma-separated string
- Convert a list of characters into a string
- Convert a list to a string in C
- Convert a namedtuple into a dictionary
- Convert a string representation of a hex dump to a byte array using Java?
- Convert any object to a byte
- Convert a Pandas DataFrame to a dictionary
- Convert a PHP object to an associative array
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

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 courseData 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.