[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.

I've got the following code:

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); 
}   

It's reading from a file, but mapper.readValue() will also accept an InputStream and you can obtain an InputStream from a string by using the following:

new ByteArrayInputStream(astring.getBytes("UTF-8")); 

There's a bit more explanation about the mapper on my blog.

Answer from djna on Stack Overflow
🌐
GitHub
github.com › FasterXML › jackson-databind › discussions › 4330
handling Map<String,Object> of known types but not polymorphic · FasterXML/jackson-databind · Discussion #4330
I could use a different customised ObjectMapper in a few instances if necessary. Otherwise, is there a (mostly) de-serialisation hook I can use on something like that · @JsonXYZ(MyMapObjectValueDeserialiser.class) private Map<String,Object> config;
Discussions

Parse properties to Map<String, Object>
JavaPropsMapper mapper = JacksonMapperHolder.getJavaPropsMapper(); Map result = mapper.readValue("level1=value1\nlevel1.level2=value2", new TypeReference>() {}); More on github.com
🌐 github.com
January 31, 2023
java - Deserialize to a Map<String, Object> with correct type for each value - Stack Overflow
For example, in the sample above, ... as a String. I've seen examples for basing what type on a variety of things, but in my scenario, I won't know what the types are (they will be user generated objects that I won't know in advance), so I need to be able to serialize the type information with the key value pair. How can I accomplish this with Jackson... More on stackoverflow.com
🌐 stackoverflow.com
June 7, 2019
Deserializing into Map<String, Object> based on a map-global type property
Hi all, I need to serialize and deserialize a Map containing dynamic properties of different types. As such, there is no Bean-based solution possible. The possible types of pr... More on github.com
🌐 github.com
1
1
Jackson mapping of JSON to Java Map<String, Map<String, String> not working correctly with annotations
Without more details (can you share the full class that values is in, and the full json you are sending, possible in a simple Java main? Plus the full error message), I'm assuming that you are using Jackson, and that this values is in a larger class you are trying to deserialize. If so, jackson is expecting the {"value1":{...}} to be inside a greater object with a field called values, since that is the name of the field that contains the map. If that is the case, consider @JsonAnyGetter and @JsonAnySetter there instead, so that Jackson will pack all properties into that object, rather than looking for the property inside the json data. More on reddit.com
🌐 r/javahelp
7
6
February 2, 2016
🌐
Baeldung
baeldung.com › home › json › jackson › map serialization and deserialization with jackson
Map Serialization and Deserialization with Jackson | Baeldung
January 8, 2024 - Here we’re telling Jackson to deserialize the Map<MyPair, String> contained in ClassWithAMap, so we need to extend KeyDeserializer to describe how to deserialize the map’s key, a MyPair object, from an input String:
🌐
Mkyong
mkyong.com › home › java › convert json string to map using jackson
Convert JSON string to Map using Jackson | mkyong.com
April 23, 2024 - This example parses JSON string to a Map using Jackson. String json = "..."; ObjectMapper mapper = new ObjectMapper(); // convert JSON string to Map Map<String, Object> map = mapper.readValue(json, new TypeReference<>() {});
🌐
Stack Abuse
stackabuse.com › convert-json-string-to-java-map-with-jackson
Convert JSON String to Java Map with Jackson
March 16, 2023 - String json = "{\n" + "\"Task 1\" : \"In_Progress\",\n" + "\"Task 2\" : \"Done\",\n" + "\"Task 3\" : \"Planned\"\n" + "}"; // ObjectMapper instantiation ObjectMapper objectMapper = new ObjectMapper(); // Deserialization into a Map Map<String, TASK_STATUS> result = objectMapper.readValue(json, HashMap.class); // Printing the results System.out.println(result.entrySet()); We've chucked the json contents into the readValue() method, and since it contains JSON that can be deserialized into a Map, given the key-value pairings, told Jackson to deserialize into a HashMap.
🌐
Baeldung
baeldung.com › home › json › jackson › intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){}); One of the greatest strengths of the Jackson library is the highly customizable serialization and deserialization process.
🌐
GitHub
github.com › FasterXML › jackson-dataformats-text › issues › 376
Parse properties to Map<String, Object> · Issue #376 · FasterXML/jackson-dataformats-text
January 31, 2023 - JavaPropsMapper mapper = JacksonMapperHolder.getJavaPropsMapper(); Map<String, Object> result = mapper.readValue("level1=value1\nlevel1.level2=value2", new TypeReference<Map<String, Object>>() {});
🌐
Makeinjava
makeinjava.com › home › convert map to/from json string in java (jackson objectmapper/ example)
Convert Map to/from JSON string in java (jackson objectmapper example)
January 1, 2024 - Given Map of String and object, serialize map of String and user defined objects or POJOs to corresponding JSON and vice versa using Jackson ObjectMapper
Find elsewhere
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-json-string-to-map
Convert JSON String to Map using Jackson
October 14, 2022 - try { // create a map Map<String, Object> map = new HashMap<>(); map.put("name", "John Deo"); map.put("email", "john.doe@example.com"); map.put("roles", new String[]{"Member", "Admin"}); map.put("admin", true); // convert map to JSON string String json = new ObjectMapper().writeValueAsString(map); // print JSON string System.out.println(json); } catch (Exception ex) { ex.printStackTrace(); } You should see the following JSON printed on the console: {"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com"} If you want to write the converted Map directly to a JSON file, use the writeValue() method instead: new ObjectMapper().writeValue(Paths.get("user.json").toFile(), map); For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-objectmapper.html
Jackson ObjectMapper
This can be useful if you do not know ahead of time the exact JSON structure that you will be parsing. Usually you will be reading a JSON object into a Java Map. Each field in the JSON object will become a key, value pair in the Java Map. Here is an example of reading a Java Map from a JSON String with the Jackson ObjectMapper:
Top answer
1 of 1
24

I think the simplest way of achieve what you want is using:

ObjectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

This will add type information in the serialized json.

Here you are a running example, that you will need to adapt to Spring:

public class Main {
    
    public enum MyEnum {
        enumValue1
    }
        
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
            
        MyClass obj = new MyClass();
        obj.setContext(new HashMap<String, Object>());
            
        obj.setVal1("foo");
        obj.setVal2("var");
        obj.getContext().put("key1", "stringValue1");
        obj.getContext().put("key2", MyEnum.enumValue1);
        obj.getContext().put("key3", 3.0);

        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            
        System.out.println(json);
            
        MyClass readValue = mapper.readValue(json, MyClass.class);
        //Check the enum value was correctly deserialized
        Assert.assertEquals(readValue.getContext().get("key2"), MyEnum.enumValue1);
    }
}

The object will be serialized into something similar to:

[ 
  "so_27871226.MyClass", 
  {
    "val1" : "foo",
    "val2" : "var",
    "context" : [ 
      "java.util.HashMap", 
      {
        "key3" : 3.0,
        "key2" : [ "so_27871226.Main$MyEnum", "enumValue1" ],
        "key1" : "stringValue1"
      } 
    ]
  } 
]

And will be deserialized back correctly, and the assertion will pass.

By the way, there are more ways of doing this, please look at https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization for more info.

I hope it will help.

🌐
YouTube
youtube.com › watch
How To Convert Java Map Object to/from JSON String using Jackson API | Java Inspires - YouTube
In this video, we will see how to convert Java Map object to from JSON String using Jackson API.https://javainspires.blogspot.com/2021/06/jackson-api-how-to-...
Published: June 11, 2021
🌐
GitHub
github.com › FasterXML › jackson-databind › discussions › 4341
Deserializing into Map<String, Object> based on a map-global type property · FasterXML/jackson-databind · Discussion #4341
This type defines all possible Map entries and their types. ... The serialization part is trivial, as the Java types are known. However, after trying for very long already, I simply cannot get the deserialization part working: I could write a Deserializer for the complete JSON. Then, however, I cannot use all the nice Jackson features for other properties.
🌐
Reddit
reddit.com › r/javahelp › jackson mapping of json to java map not working correctly with annotations
r/javahelp on Reddit: Jackson mapping of JSON to Java Map<String, Map<String, String> not working correctly with annotations
February 2, 2016 -

Hi,

As the title states, I am trying to map the following JSON data

{ "value1" : { "key1":"value1", "key2":"value2"}}

The class to map this is has a field

@JsonProperty
private Map<String, Map<String, String>> values;

Jackson says unknown property value1, well I want value1 to be the key to the map and the rest of the object to populate the value Map<String, String>. There could be several key -> Map<String, String> lines in the Json object. Also the key value1 is based on what was searched for, for example if I search for 100 I will get

{"100": {"key1":"value1", "key2":"value2"}}

it also needs to support multiple response lines e.g

{"100" : {"key1":"value1" , "key2" : "value2" },
  "101" : {"key1":"value1",  "key2" : "value2"}}

thanks

🌐
Educative
educative.io › answers › how-to-convert-a-json-string-to-a-map-using-jackson
How to convert a JSON string to a map using Jackson
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0-rc1</version> </dependency> Create an object of the ObjectMapper class.
Top answer
1 of 1
4

You need to use Object as Map value because it could be another Map, List or primitive (String, Integer, etc.). Jackson allows also to manipulate JSON using JsonNode types. We need to traverse JSON object but also JSON array (you forgot about it). In that case we need to:

  • Deserialise JSON to JsonNode.
  • Traverse it using JsonNode API.
  • Convert to the Map

Simple implementation:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        String json = "{\"Key1\": \"value1\", \"Key2\": { \"Key2.1\": \"value2.1\" }, \"Key3\":[{\"pRiMe\":11}]}";
        Map<String, Object> map = convertJsonStringToMap(json);

        System.out.println(map);
    }

    private static Map<String, Object> convertJsonStringToMap(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(json);
        transformKeys(node);

        TypeReference mapType = new TypeReference<Map<String, Object>>() {
        };

        return mapper.convertValue(node, mapType);
    }

    private static void transformKeys(JsonNode parent) {
        if (parent.isObject()) {
            ObjectNode node = (ObjectNode) parent;

            List<String> names = new ArrayList<>();
            node.fieldNames().forEachRemaining(names::add);

            names.forEach(name -> {
                JsonNode item = node.remove(name);
                transformKeys(item);
                node.replace(name.toLowerCase(), item);
            });
        } else if (parent.isArray()) {
            ArrayNode array = (ArrayNode) parent;
            array.elements().forEachRemaining(JsonApp::transformKeys);
        }
    }
}

Above code prints:

{key1=value1, key2={key2.1=value2.1}, key3=[{prime=11}]}

We got rid of unsafe casting and our implementation is more concise.

🌐
GitHub
github.com › codehaus › jackson › blob › master › src › test › org › codehaus › jackson › map › deser › TestMapDeserialization.java
jackson/src/test/org/codehaus/jackson/map/deser/TestMapDeserialization.java at master · codehaus/jackson
November 26, 2022 - assertEquals("string", map.get("string").getObject()); assertEquals(Boolean.TRUE, map.get("boolean").getObject()); assertEquals(Collections.singletonList("list0"), map.get("list").getObject()); assertTrue(map.containsKey("null")); assertNull(map.get("null")); assertEquals(5, map.size()); } · // [JACKSON-620]: allow "" to mean 'null' for Maps · public void testFromEmptyString() throws Exception · { ObjectMapper m = new ObjectMapper(); m.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); Map<?,?> result = m.readValue(quote(""), Map.class); assertNull(result); } ·
Author: codehaus
🌐
Java Guides
javaguides.net › 2023 › 10 › convert-json-string-to-map-in-java.html
Convert JSON string to Map in Java
October 26, 2023 - import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class MainApp { public static void main(String[] args) { // Sample JSON string String jsonStr = "{\"id\":1,\"name\":\"Jane Smith\",\"email\":\"jane.smith@example.com\"}"; // Create an ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); try { // Convert JSON string to Map Map<String, Object> map = mapper.readValue(jsonStr, Map.class); // Display the map for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } } }
🌐
QA Automation Expert
qaautomation.expert › 2021 › 11 › 22 › serialization-how-to-convert-map-to-json-string-using-jackson-api
Serialization – How to convert Map to JSON string using Jackson API
December 8, 2022 - This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API.