Home >Java >javaTutorial >How to Efficiently Convert JSON to a Map in Java?
Converting JSON to Map in Java
When working with Java, you may encounter the need to convert a JSON code into a Map data structure. This can be achieved using external libraries or by writing your own custom parser.
One recommended approach involves leveraging libraries provided by json.org. Among these libraries, Jackson stands out for its simplicity. With Jackson, the conversion can be done as follows:
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; // Initialize the source JSON String jsonSource = "{ \"data\" : { \"field1\" : \"value1\", \"field2\" : \"value2\" } }"; // Create a new ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Convert JSON to Map using HashMap class for value type Map<String, Object> result = mapper.readValue(jsonSource, HashMap.class);
By using Jackson, you can easily convert the provided JSON into a Map, where keys represent the field names ("field1", "field2"), and values represent the corresponding values ("value1", "value2"). This solution is efficient and widely used for JSON parsing in Java.
The above is the detailed content of How to Efficiently Convert JSON to a Map in Java?. For more information, please follow other related articles on the PHP Chinese website!