Home > Java > javaTutorial > body text

How to Convert a JSON String to a Map using Jackson in Java?

Linda Hamilton
Release: 2024-10-30 21:03:03
Original
655 people have browsed it

How to Convert a JSON String to a Map<String, String> using Jackson in Java? 
using Jackson in Java? " />

How to Convert a JSON String to a Map with Jackson JSON

Question:

Attempting to convert a JSON string to a Map using Jackson leads to an "Unchecked assignment Map to Map" error. Seeking the correct approach and exploring alternative methods for JSON conversion in Java, similar to json_decode in PHP.

Answer:

The correct approach using Jackson JSON is to leverage a TypeReference to specify the desired map type as follows:

<code class="java">public void testJackson() throws IOException {  
    ObjectMapper mapper = new ObjectMapper(); 
  
    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

For reading from a string, obtain an InputStream using new ByteArrayInputStream(astring.getBytes("UTF-8")) and pass it to mapper.readValue().

Alternative Native Java JSON Conversion:

Jackson is not the only option for JSON conversion in Java. The Gson library from Google provides a more intuitive approach:

  1. Import the Gson class.
  2. Create a Gson object.
  3. Use Gson.fromJson() to convert a JSON string to the desired object type, in this case, a Map.

Additional Note:

The original answer has been updated to reflect the recommendation for using the Gson library instead of Jackson.

The above is the detailed content of How to Convert a JSON String to a Map using Jackson in Java?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!