Thursday 18 October 2012

How to create JSON object and read back as java object using jackson api


//Sample Example to convert Java Map object to JSON object using jackson API.

package com.json.jackson.example;

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 JavaMap2JSON {

 public static void main(String args[]) {

  ObjectMapper objMapper = new ObjectMapper();
  Map<String, Object> userMap = new HashMap<String, Object>();
  userMap.put("name", "Gaurav");
  userMap.put("age", 32);
  List<Object> list = new ArrayList<Object>(0);

  list.add("MUMBAI");
  list.add("HYDERABAD");
  list.add("ANDHRA PRADESH");

  userMap.put("messages", list);

  try {
           objMapper.writeValue(new File("C:\\userMap.JSON"), userMap);
           System.out.println("User Map Converted Successfully");
                } catch (JsonGenerationException jge) {
              jge.printStackTrace();
        } catch (JsonMappingException jme) {
     jme.printStackTrace();
  } catch (IOException ioe) {
     ioe.printStackTrace();
    }
  }
}


//Sample Example to read JSON object back into JAVA object using jackson API.

package com.json.jackson.example;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JSON2JavaMapConvertion {

 public static void main(String args[]) {
  ObjectMapper objMapper = new ObjectMapper();
  try {
           Map<String, Object> userMap = objMapper.readValue(new File("C:\\userMap.JSON"),
           new TypeReference<Map<String, Object>>() {
     });
           System.out.println("Name -" + userMap.get("name"));
           System.out.println("Age -" + userMap.get("age"));

 @SuppressWarnings("unchecked")
   ArrayList<String> alist = (ArrayList<String>) userMap.get("messages");

for (String listVal : alist) {
    System.out.println("List Values are-" + listVal);
                }
              } catch (JsonGenerationException jge) {
           jge.printStackTrace();
        } catch (JsonMappingException jme) {
       jme.printStackTrace();
      } catch (IOException ioe) {
     ioe.printStackTrace();
    }
  }
}
Note:- For the Execution of above programs jackson API is required.

No comments:

Post a Comment