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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 21:03:03630browse

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>

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!

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