Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Monday, 15 April 2013

Convert JSON String to Java object using Jackson

Leave a Comment

This method takes an Jon String which represent a User object in JSON format and convert it into Java User object. In this Java example I have create User as nested static class for convenience, You may create a separate top level class if needed.

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/*
 * Java program to convert JSON String into Java object using Jackson library.
 * Jackson is very easy to use and require just two lines of code to create a Java object
 * from JSON String format.
 *
 * @author Harit Rajput
 */
public class JsonToJavaConverter {

        private static Logger logger = Logger.getLogger(JsonToJavaConverter.class);
      
      
        public static void main(String args[]) throws JsonParseException
                                                    , JsonMappingException, IOException{

                JsonToJavaConverter converter = new JsonToJavaConverter();
              
                String json = "{\n" +
                "    \"name\": \"Harit\",\n" +
                "    \"surname\": \"Kumar\",\n" +
                "    \"phone\": 9832734651}";
              
                //converting JSON String to Java object
                converter.fromJson(json);
        }
      
      
        public Object fromJson(String json) throws JsonParseException
                                                   , JsonMappingException, IOException{
                User obj = new ObjectMapper().readValue(json, User.class);
                logger.info("Java Object created from JSON String ");
                logger.info("JSON String : " + json);
                logger.info("Java Object : " + obj);
              
                return obj;
        }
      
public static class User{
                private String name;
                private String surname;
                private long phone;
              
                public String getName() {return name;}
                public void setName(String name) {this.name = name;}

                public String getSurname() {return surname;}
                public void setSurname(String surname) {this.surname = surname;}

                public long getPhone() {return phone;}
                public void setPhone(long phone) {this.phone = phone;}

                @Override
                public String toString() {
                        return "User [name=" + name + ", surname=" + surname + ", phone="
                                        + phone + "]";
                }
              
               
        }
}



Output:
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object created from JSON String
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - JSON String : {
    "name": "Harit",
    "surname": "Kumar",
    "phone": 9787878788}
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object : User [name=Harit, surname=Kumar, phone=9787878788]


Read More...

Thursday, 4 April 2013

JSON to Object Mapping using Jackson

Leave a Comment

JSON:

{
"recentVideosList":[{"tags":null,"followerId":null,"videoId":"hLta6iJGtH8=","videoViewCount":"0","title":"twitter2","videoURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.mov","userFollowingThisVideo":"No","videosByThisUser":"5","videoTimer":"6","videoUploadDateTime":"2013-03-25 07:41:49.0","isAlreadyFlagged":"N","uploadedByCountryId":"96","uploadedByUserId":"xHj2V0LLsfE=","thumbnailURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.png","aboutUploadedBy":"ddddddddretreyreyrtyrt","tips":"0","uploadedBy":"naveen140990","abuseCount":"0","videoShareCount":"0","isAlreadyLiked":"NO"}],

"challengeOfTheDayList":[{"notificationId":"1","notificationDescription":"This is the first notification of videos."}],

"videoOfTheDayList":[{"tags":null,"followerId":null,"videoId":"jFB425S0Rv0=","videoViewCount":"9","title":"shr","videoURL":"https://s3.amazonaws.com/youbusk/2/1360314335_608470.mov","userFollowingThisVideo":"No","videosByThisUser":"6","videoTimer":"16","videoUploadDateTime":"2013-02-08 14:32:00.0","isAlreadyFlagged":"Y","uploadedByCountryId":"241","uploadedByUserId":"jFB425S0Rv0=","thumbnailURL":"https://s3.amazonaws.com/youbusk/2/1360314335_608470.png","aboutUploadedBy":"","tips":"14","uploadedBy":"gaurav11","abuseCount":"3","videoShareCount":"0","isAlreadyLiked":"YES"}],

"totalDataRequested":"2",
"totalDataSent":"2",
"responseCode":"4060",
"responseDescription":"Home service sent successfully."
}

JsonToObject.java

package com;

import java.io.IOException;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonToObject{

 public CustomBean jsonConvertor(String jsonString)
 {
  JsonFactory factory = new JsonFactory();
  ObjectMapper mapper = new ObjectMapper(factory);
  try 
  {
   CustomBean customBean = mapper.readValue(jsonString, CustomBean.class);
   
   return customBean;
  } catch (JsonParseException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
   return new CustomBean();
 }
}

CustomBean

package com;

import java.util.List;

public class CustomBean {

 private List recentVideosList;
 private List videoOfTheDayList;
 private List challengeOfTheDayList;
 private String totalDataRequested;
 private String totalDataSent;
 private String responseCode;
 private String responseDescription;
 
 public List getRecentVideosList() {
  return recentVideosList;
 }
 public void setRecentVideosList(List recentVideosList) {
  this.recentVideosList = recentVideosList;
 }
 public List getVideoOfTheDayList() {
  return videoOfTheDayList;
 }
 public void setVideoOfTheDayList(List videoOfTheDayList) {
  this.videoOfTheDayList = videoOfTheDayList;
 }
 public List getChallengeOfTheDayList() {
  return challengeOfTheDayList;
 }
 public void setChallengeOfTheDayList(
   List challengeOfTheDayList) {
  this.challengeOfTheDayList = challengeOfTheDayList;
 }
 public String getTotalDataRequested() {
  return totalDataRequested;
 }
 public void setTotalDataRequested(String totalDataRequested) {
  this.totalDataRequested = totalDataRequested;
 }
 public String getTotalDataSent() {
  return totalDataSent;
 }
 public void setTotalDataSent(String totalDataSent) {
  this.totalDataSent = totalDataSent;
 }
 public String getResponseCode() {
  return responseCode;
 }
 public void setResponseCode(String responseCode) {
  this.responseCode = responseCode;
 }
 public String getResponseDescription() {
  return responseDescription;
 }
 public void setResponseDescription(String responseDescription) {
  this.responseDescription = responseDescription;
 }
 
}


Read More...

Saturday, 15 December 2012

Jackson Tree Model Example

Leave a Comment

In Jackson, you can use “Tree Model” to represent JSON, and perform the read and write operations via “JsonNode“, it is similar to DOM tree for XML. See code snippet :
 ObjectMapper mapper = new ObjectMapper();
 
 BufferedReader fileReader = new BufferedReader(
  new FileReader("c:\\user.json"));
 JsonNode rootNode = mapper.readTree(fileReader);
 
 /*** read value from key "name" ***/
 JsonNode nameNode = rootNode.path("name");
 System.out.println(nameNode.getTextValue());

This time, we show you how to read the JSON string from “file.json” into a “Tree“, and also how to read and and update those values via JsonNode.
File : file.json
{
  "age" : 29,
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "harit"
 }
See full example, it should be self-explanatory.
package com;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
 
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
 
public class JacksonTreeNodeExample {
 public static void main(String[] args) {
 
  ObjectMapper mapper = new ObjectMapper();
 
  try {
 
   BufferedReader fileReader = new BufferedReader(
    new FileReader("c:\\user.json"));
   JsonNode rootNode = mapper.readTree(fileReader);
 
   /*** read ***/
   JsonNode nameNode = rootNode.path("name");
   System.out.println(nameNode.getTextValue());
 
   JsonNode ageNode = rootNode.path("age");
   System.out.println(ageNode.getIntValue());
 
   JsonNode msgNode = rootNode.path("messages");
   Iterator<JsonNode> ite = msgNode.getElements();
 
   while (ite.hasNext()) {
    JsonNode temp = ite.next();
    System.out.println(temp.getTextValue());
 
   }
 
   /*** update ***/
   ((ObjectNode)rootNode).put("nickname", "new nickname");
   ((ObjectNode)rootNode).put("name", "updated name");
   ((ObjectNode)rootNode).remove("age");
 
   mapper.writeValue(new File("c:\\user.json"), rootNode);
 
  } catch (JsonGenerationException e) {
 
   e.printStackTrace();
 
  } catch (JsonMappingException e) {
 
   e.printStackTrace();
 
  } catch (IOException e) {
 
   e.printStackTrace();
 
  }
 
 }
 
}
Output
harit
29
msg 1
msg 2
msg 3
And the file “c:\\file.json” is updated with following new content :
{
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "updated name",
  "nickname" : "new nickname"
}

Read More...

How To Convert Java Map To / From JSON (Jackson)

Leave a Comment

This time, we are doing the same, but replace user define object with Map.
Map is more suitable in a simple and short JSON processing, for complex JSON structure, you should always create an user defined object for easy maintainability.
In this tutorial, we show you how to use Map to construct the JSON data, write it to file. And also how to read JSON from file, and display each value via Map.

1. Write JSON to file

Jackson example to use Map to construct the entire JSON data structure, then write it to file named “user.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 org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
     public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 Map<String, Object> userInMap = new HashMap<String, Object>();
 userInMap.put("name", "harit");
 userInMap.put("age", 29);
 
 List<Object> list = new ArrayList<Object>();
 list.add("msg 1");
 list.add("msg 2");
 list.add("msg 3");
 
 userInMap.put("messages", list);
 
 try {
 
   // write JSON to a file
   mapper.writeValue(new File("c:\\user.json"), userInMap);
 
 } catch (JsonGenerationException e) {
   e.printStackTrace();
 } catch (JsonMappingException e) {
   e.printStackTrace();
 } catch (IOException e) {
   e.printStackTrace();
 }
     }
}
Output – user.json
{
 "age":29,
 "name":"harit",
 "messages":["msg 1","msg 2","msg 3"]
}

2. Read JSON from file

Read JSON data from file, convert it to Map and display the values.
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 JacksonExample {
     public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
    // read JSON from a file
    Map<String, Object> userInMap = mapper.readValue(
  new File("c:\\user.json"), 
  new TypeReference<Map<String, Object>>() {});
 
    System.out.println(userInMap.get("name"));
    System.out.println(userInMap.get("age"));
 
    ArrayList<String> list = 
  (ArrayList<String>) userInMap.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
harit
29
msg 1
msg 2
msg 3
Read More...

How To Convert Java Object To / From JSON (Jackson)

3 comments

JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a very good alternative solution.
In this series of Java JSON tutorials, we focus on three popular third party Java libraries to process JSON data, which areJacksonGoogle Gson and JSON.simple
For object/json conversion, you need to know following two methods :
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Note
Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

1. Jackson Dependency

Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion.

2. POJO

An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.
package json;
 
import java.util.ArrayList;
import java.util.List;
 
public class User {
 
 private int age = 29;
 private String name = "harit";
 private List<String> messages = new ArrayList<String>() {
  {
   add("msg 1");
   add("msg 2");
   add("msg 3");
  }
 };
 
 //getter and setter methods
 
 @Override
 public String toString() {
  return "User [age=" + age + ", name=" + name + ", " +
    "messages=" + messages + "]";
 }
}

3. Java Object to JSON

Convert an “user” object into JSON formatted string, and save it into a file “user.json“.
package json;
 
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 User user = new User();
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // convert user object to json string, and save to a file
  mapper.writeValue(new File("c:\\user.json"), user);
 
  // display to console
  System.out.println(mapper.writeValueAsString(user));
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
Output
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"harit"}
Note
Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

4. JSON to Java Object

Read JSON string from file “user.json“, and convert it back to Java object.
package json;
 
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // read from file, convert it to user class
  User user = mapper.readValue(new File("c:\\user.json"), User.class);
 
  // display to console
  System.out.println(user);
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
User [age=29, name=harit, messages=[msg 1, msg 2, msg 3]]

Read More...