Converting JSON String to Map
To convert a JSON string to a Map
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!