Jackson – Convert JSON string to Map

In Jackson, we can use mapper.readValue(json, Map.class) to convert a JSON string to a Map

P.S Tested with Jackson 2.9.8

pom.xml

	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.9.8</version>
	</dependency>

1. JSON string to Map

JacksonMapExample1.java

package com.mkyong;

import com.fasterxml.jackson.databind.ObjectMapper;

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

public class JacksonMapExample1 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"name\":\"mkyong\", \"age\":\"37\"}";

        try {

            // convert JSON string to Map
            Map<String, String> map = mapper.readValue(json, Map.class);

			// it works
            //Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});

            System.out.println(map);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output


{name=mkyong, age=37}

2. Map to JSON string

JacksonMapExample2.java

package com.mkyong;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JacksonMapExample2 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        Map<String, String> map = new HashMap<>();
        map.put("name", "mkyong");
        map.put("age", "37");

        try {

            // convert map to JSON string
            String json = mapper.writeValueAsString(map);

            System.out.println(json);   // compact-print

            json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);

            System.out.println(json);   // pretty-print

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


    }
}

Output


{"name":"mkyong","age":"37"}
{
  "name" : "mkyong",
  "age" : "37"
}

3. JSON Array to Map?

3.1 JSON array string like this


[{"age":29,"name":"mkyong"}, {"age":30,"name":"fong"}]

It should convert to a List, instead of a Map, for example :


	// convert JSON array to List
	List<Person> list = Arrays.asList(mapper.readValue(json, Person[].class));

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
22 Comment threads
11 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
24 Comment authors
Shantanu MoreAnonymousAnimeshergrgZeeshan Abbas Recent comment authors
newest oldest most voted
Lenin
Guest
Lenin

greate Post!!.
I m looking for jar file. Can you provide me the link to download.

FJ
Guest
FJ

I am getting
Exception in thread “main” com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: {“name”:”mkyong”, “age”:29}; line: 1, column: 1]

Am i missing something ?

ergrg
Guest
ergrg

change to “new
TypeReference
<Map

>(){} ”
so that the type would be consistent

ergrg
Guest
ergrg

change to “new
TypeReference
<Map

\>\(){} ”
so that the type would be consistent

Zeeshan Abbas
Guest
Zeeshan Abbas

4. JSON file to Map
for proper json data more then one element it shows error?
[
{“name”:”mkyong”,”messages”:[“msg 1″,”msg 2″,”msg 3″],”age”:29},
{“name”:”mkyong”,”messages”:[“msg 1″,”msg 2″,”msg 3″],”age”:29}
]

Anonymous
Guest
Anonymous

Hi Mkyong,

What could I use if I have a JSON array like so:

[{“age”:”29″,”name”:”mkyong”}, {“age”:”30″,”name”:”mfong”}]

???

I tried using .readValue as in your first demonstration, but the result map contains only the first json object above, i.e. {“age”:”29″,”name”:”mkyong”}. I need a way to traverse a huge json array, please help!

Echo
Guest
Echo

You can have a try:
User[] userArray = mapper.readValue(new File(“c:\user.json”), new TypeReference<Map() {});

Shantanu More
Guest
Shantanu More

for converting JSON Array to Map,why it should convert to a List, instead of a Map? Could you elaborate it?

Anonymous
Guest
Anonymous

This is a good and handy tutorial to udnerstand mapper functions and use them. Is there a way to not convert a json field’s value from being converted to string. For eg: when converting a java object Map(String,Object) to a json string using writeValueAsString() method . One of the key is my JSON(“value”) is Object data type, I don’t want its value to be converted to a string (“43”) , can we restrict this in someway ?
Eg:
{ “id”: “devID”,
“value”: 43
}

punk
Guest
punk

Hi,i have json array as string eg: [{“toDate”:”30/09/2017 23:59:59″,”fromDate”:”01/04/2017 00:00:00″,”effectiveDate”:”01/04/2017 00:00:00″}] m getting the

Giampiero Granatella
Guest
Giampiero Granatella

Hi, thank you for the example
Just a note:
Example 1

Map map = new HashMap();

// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map>(){});

Should be according to the declaration
map = mapper.readValue(json, new TypeReference<Map>(){});

Giampiero Granatella
Guest
Giampiero Granatella

TypeReference<Map …
must be
TypeReference<Map …

Jochem Broekhoff
Guest
Jochem Broekhoff

Tested for Jackson 2.7.4.

ben
Guest
ben

What is I have this JSON, how to convert it to Object

{“replace”:{“T”:”Yes”,”default”,”No”}}

Naoomi
Guest
Naoomi

If the value of Map.get will be Null, what I need to write to accept Null Value?

Z
Guest
Z

Just what i was looking for, works perfectly. Thanks!

Tiago
Guest
Tiago

URGENT:

I’am trying to implement the first exemple into an android app, but when the program runs the instruction,

ObjectMapper mapper = new ObjectMapper();

the program stops… I don’t know why.

What i want is to recive a json string and convert it into a map.

Thanks.

Astonkacser
Guest
Astonkacser

This is exactly what I was looking for. Thanks!

Kirtan
Guest
Kirtan

thanks…

mukesh.pandey
Guest
mukesh.pandey

sir please tell me how to send json data from java class to jsp page …
and if possible then give example to display data in grid form using jquery in struts2.

Deepak Sabharwal
Guest
Deepak Sabharwal

u r awesome yaar…i love mkyong … it has helped me many times…

sachin
Guest
sachin

i need help i m trying to convert a csv file to json script can u give code for that also …..having problem please help…

mobinga
Guest
mobinga

Thank you for this simple tutorial.

Nelson
Guest
Nelson

do you compare this functionality with gson? I am interested to see whether it can be done in gson easily. Because there are many different json library, I am trying to find one good to use in most of the cases and stick with it. :)

trackback
Java JSON Tutorial

[…] JSON Example to use ObjectMapper writeValue() and readValue() to convert Java object to / from JSON.Jackson data binding example – Map & JSON Example to convert Java Map to / from JSONJackson Tree Model example Read JSON into Tree, like DOM […]

Animesh
Guest
Animesh

Hi Mkyong,

What could I use if I have a JSON array like so:

{[{“age”:”29″,”name”:”mkyong”}, {“age”:”30″,”name”:”mfong”}]}

Please provide the full code.