SoFunction
Updated on 2025-04-29

How to convert JSON format string to Map in Java

In Java, convert JSON format strings toMapIt can be implemented with some popular JSON processing libraries. The following introduces you to the methods of using two common libraries, Gson and Jackson.

Using the Gson library

Gson is a Java library developed by Google for processing JSON data. It can be used to easily convert JSON strings toMap
You need to add Gson dependencies to the project first. If you are using a Maven project, you canAdd the following dependencies to:

<dependency>
    <groupId></groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>

Here is the sample code:

import ;
import ;
public class JsonToMapWithGson {
    public static void main(String[] args) {
        String json = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
        Gson gson = new Gson();
        // Convert JSON string to Map        Map&lt;String, Object&gt; map = (json, );
        // Output the converted Map        (map);
    }
}

Code explanation:

1. Create a JSON string: defines a string in JSON formatjson

2. Create a Gson instance: UseGsonCreate a classGsonObjectgson

3. Convert toMap: Call()Method, convert JSON string toMap<String, Object>Object of type.

4. Output result: Print convertedMap

Using the Jackson library

Jackson is another popular Java JSON processing library that also provides the conversion of JSON strings toMapfunction.
If you use the Maven project, you need toAdd the following dependencies to:

<dependency>
    <groupId></groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

Here is the sample code:

import ;
import ;
public class JsonToMapWithJackson {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        // Convert JSON string to Map        Map&lt;String, Object&gt; map = (json, );
        // Output the converted Map        (map);
    }
}

Code explanation:

1. Create a JSON string: defines a string in JSON formatjson

2. CreateObjectMapperExample: UseObjectMapperCreate a classObjectMapperObjectobjectMapper

3. Convert toMap: Call()Method, convert JSON string toMap<String, Object>Object of type.

4. Output result: Print convertedMap

Here is the article about how to convert JSON format strings to Map in Java? That’s all for the article. For more related JSON string conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!