Main Tutorials

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 Author

author image
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

Subscribe
Notify of
34 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Lenin
8 years ago

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

FJ
7 years ago

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
5 years ago
Reply to  FJ

change to “new
TypeReference
<Map

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

ergrg
5 years ago
Reply to  FJ

change to “new
TypeReference
<Map

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

Zeeshan Abbas
6 years ago

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
9 years ago

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
8 years ago
Reply to  Anonymous

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

Anonymous
5 years ago

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
}

Zack Green
3 years ago

I am trying to Convert a JSON file obtained by calling ‘getjson.php’ returns a record like this:

[{“id”:”1″,”incident_lat”:”33.39313″,”incident_lon”:”-104.52276″,”incident_name”:”The Roswell incident”,”incident_date”:”1947-07-04″,”incident_info”:”The famous Roswell Incident.”},{“id”:”2″,”incident_lat”:”52.083946″,”incident_lon”:”1.4332807″,”incident_name”:”Rendelsham Forest”,”incident_date”:”1980-12-26″,”incident_info”:”The Famous Rendelsham Forest Incident”},{“id”:”3″,”incident_lat”:”30.365765″,”incident_lon”:”-88.54731″,”incident_name”:”The Pascagoula Incident”,”incident_date”:”1973-10-11″,”incident_info”:”The famous Pascagoula Incident”}]

But I am having problems calling getjson.php from List create list in JS what would be the best way to do this?.

I have tried
List<Incident> list = Arrays.asList(mapper.readValue(‘getjson.php’, Incident[].class));

Anonymous
4 years ago

Hi,

How can I convert JSON string to map using Jackon where key in the map is Long?

Shantanu More
4 years ago

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

Animesh
5 years ago

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.

punk
6 years ago

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
6 years ago

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
6 years ago

TypeReference<Map …
must be
TypeReference<Map …

Jochem Broekhoff
7 years ago

Tested for Jackson 2.7.4.

ben
9 years ago

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

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

Naoomi
9 years ago

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

Z
9 years ago

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

Tiago
10 years ago

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
10 years ago

This is exactly what I was looking for. Thanks!

Kirtan
10 years ago

thanks…

mukesh.pandey
11 years ago

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
11 years ago

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

sachin
11 years ago

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
12 years ago

Thank you for this simple tutorial.

Nelson
12 years ago

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. 🙂