using Jackson in Java? " />
How to Convert a JSON String to a Map
Question:
Attempting to convert a JSON string to a Map
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:
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