Home  >  Article  >  Java  >  How do I convert a JSON string to a Map using Jackson JSON?

How do I convert a JSON string to a Map using Jackson JSON?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 14:29:02932browse

How do I convert a JSON string to a Map using Jackson JSON?

Converting JSON String to Map Using Jackson JSON

To convert a JSON string to a Map using Jackson JSON, one can't simply cast a generic Map to the desired type, as this would result in an unchecked assignment error.

Instead, the correct approach is to use the ObjectMapper class. Here's how:

<code class="java">ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String, String>> typeRef = 
                new TypeReference<Map<String, String>>() {};

Map<String, String> propertyMap = mapper.readValue(properties, typeRef);</code>

The ObjectMapper class provides methods for reading and writing JSON data. The readValue() method accepts an input source (e.g., a file, stream, or string) and a TypeReference object that specifies the desired type of the output object.

Additionally, Jackson JSON also provides a native way of converting JSON strings to Java objects without the need for casting:

<code class="java">public void testJackson() throws IOException {  
    ObjectMapper mapper = new ObjectMapper(); 
    File from = new File("albumnList.txt"); 
    TypeReference<HashMap<String,Object>> typeRef 
            = new TypeReference<HashMap<String,Object>>() {};

    HashMap<String,Object> o = mapper.readValue(from, typeRef); 
    System.out.println("Got " + o); 
}  </code>

This approach involves specifying the desired type using a TypeReference object, which can be created using an anonymous inner class. The ObjectMapper can then directly convert the JSON string to the desired type.

The above is the detailed content of How do I convert a JSON string to a Map using Jackson JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn