Home > Java > javaTutorial > 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
Release: 2024-10-30 14:29:02
Original
943 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template