We are moved to new domain
Click -> www.ehowtonow.com
Friday, 18 October 2013

Create Map to JSON using Jackson


In this tutorial we are going to see how to create JSON from map and print json as string and also write json in file
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.jackson 
3. add jackson-mapper-asl-1.9.13.jar, jackson-core-asl-1.9.13.jar into build path.
4. Create java class called MapToJSONExample under com.javatutorialscorner.jackson
MapToJSONExample .java
package com.javatutorialscorner.jackson;

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 org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class MapToJSONExample {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

ObjectMapper mapper = null;

Map<String, Object> map = null;

List<Object> tutorials = null;

try {
mapper = new ObjectMapper();
map = new HashMap<String, Object>();
map.put("name", "Java Tutorials Corner");
map.put("rank", "1");

tutorials = new ArrayList<Object>();
tutorials.add("Java");
tutorials.add("Servlet");
tutorials.add("JSP");
tutorials.add("Struts 1.x");
tutorials.add("Struts 2.x");
tutorials.add("Spring");
tutorials.add("Hibernate");
tutorials.add("Log4j");
tutorials.add("JSON");
tutorials.add("Web Services");
tutorials.add("JSF");
tutorials.add("Eclipse");

map.put("tutorials", tutorials);
String json = mapper.writeValueAsString(map);
System.out.println(json);

mapper.writeValue(new File("C:\\jtc\\javatutorialscorner.json"),
map);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Now run the program see the following output in console and also file created at specified location with following content.

{"tutorials":["Java","Servlet","JSP","Struts 1.x","Struts 2.x","Spring","Hibernate","Log4j","JSON","Web Services","JSF","Eclipse"],"rank":"1","name":"Java Tutorials Corner"}

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Create Map to JSON using Jackson Rating: 5 Reviewed By: eHowToNow