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]
0 comments:
Post a Comment