Convert JSON string to Map – Jackson

In this tutorial, we will show you few Jackson examples to convert JSON string to/from a Map.

P.S All examples are tested with Jackson 2.6.3

1. JSON string to Map

JsonMapExample.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonMapExample {

	public static void main(String[] args) {

		try {

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

			Map<String, Object> map = new HashMap<String, Object>();

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

			System.out.println(map);

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

}

Output


{name=mkyong, age=29}

2. Map to JSON string

Example to convert the Map to JSON string.

MapJsonExample.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MapJsonExample{

	public static void main(String[] args) {

		try {

			ObjectMapper mapper = new ObjectMapper();
			String json = "";

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

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

			System.out.println(json);

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

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

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

}

Output


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

3. Map to JSON File

JsonMapFileExample.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonMapFileExample {

	public static void main(String[] args) {

		try {

			ObjectMapper mapper = new ObjectMapper();

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

			List<Object> list = new ArrayList<>();
			list.add("msg 1");
			list.add("msg 2");
			list.add("msg 3");

			map.put("messages", list);

			// write JSON to a file
			mapper.writeValue(new File("c:\\user.json"), map);

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

}
c:\\user.json

{"name":"mkyong","messages":["msg 1","msg 2","msg 3"],"age":29}

4. JSON file to Map

JsonFileMapExample.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

	public static void main(String[] args) {

		try {

			ObjectMapper mapper = new ObjectMapper();

			// read JSON from a file
			Map<String, Object> map = mapper.readValue(
					new File("c:\\user.json"), 
					new TypeReference<Map<String, Object>>() {
			});

			System.out.println(map.get("name"));
			System.out.println(map.get("age"));

			@SuppressWarnings("unchecked")
			ArrayList<String> list = (ArrayList<String>) map.get("messages");

			for (String msg : list) {
				System.out.println(msg);
			}

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

}

Output


mkyong
29
msg 1
msg 2
msg 3

References

  1. Wikipedia : JSON
  2. Jackson – High-performance JSON processor
  3. Jackson 2 – Object to / from JSON

About the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
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

Lenin
Guest
Lenin

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

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

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}
]

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 […]

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
}

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.