How To Convert Json String To Coffee Object - Jackson Example

JSON stands for JavaScript object notation, is a lightweight text or string representation of an object together with apace becoming a pop information central format. Though it's pretty early on to tell that JSON is going to supersede XML every bit pop information interchange format, It is for certain providing an alternative. JSON stand upwardly for information inward 2 format either an object or an array. JSON object is an unordered collection of cardinal together with value, similar to String representation of hash table. On the other hand, JSON Array is an ordered collection of values. The primary departure between  JSON Object and  JSON array is in that place representation. JSON object is started alongside left couplet { together with ends alongside correct couplet } and cardinal values are separated using a colon (:). On the other hand, JSON Array starts alongside left bracket [ together with ends alongside correct bracket ] together with each value is separated past times comma. By looking at structure, You tin dismiss write  your JSON parser to parse JSON object or array to Java object, but y'all don't ask to. 

There are lot of opened upwardly origin library inward Java which provides tried together with tested agency of converting JSON String to Java object e.g. Jackson together with GSON. In this Java tutorial nosotros volition run across illustration of converting a JSON String to Java object using Jackson library

How to convert JSON String to Java object using Jackson

Java class e.g. User inward this case, spell code required to convert JSON String to Java object is precisely 2 lines inward fromJson(String json) method. 


This method takes an Jon String which stand upwardly for a User object inward JSON format together with convert it into Java User object. In this Java illustration I conduct maintain do User every bit nested static class for convenience, You may do a dissever top score 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 plan to convert JSON String into Java object using Jackson library.
 * Jackson is really slow to purpose together with require precisely 2 lines of code to do a Java object
 * from JSON String format.
 *
 * @author http://javarevisited.blogspot.com
 */
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\": \"Garima\",\n" +
                "    \"surname\": \"Joshi\",\n" +
                "    \"phone\": 9832734651}";
              
                //converting JSON String to Java object
                converter.fromJson(json);
        }
      
      
        public Object fromJson(String json) throws JsonParseException
                                                   , JsonMappingException, IOException{
                User garima = new ObjectMapper().readValue(json, User.class);
                logger.info("Java Object created from JSON String ");
                logger.info("JSON String : " + json);
                logger.info("Java Object : " + garima);
              
                return garima;
        }
      
      
        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=" + mention + ", surname=" + surname + ", phone="
                                        + outcry + "]";
                }
              
               
        }
}

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": "Garima",
    "surname": "Joshi",
    "phone": 9832734651}
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object : User [name=Garima, surname=Joshi, phone=9832734651]


Dependency
As I said, You tin dismiss either purpose Jackson or Gson to convert JSON String to Java object together with inward this Java tutorial nosotros conduct maintain used Jackson library for JSON to Java object conversion. If y'all are using Maven for dependency administration than y'all tin dismiss add together next dependency inward POM.xml :

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-xc</artifactId>
      <version>1.9.11</version>
</dependency>

Or y'all tin dismiss precisely add together next JAR files into your application’s classpath :

jackson-xc-1.9.11.jar
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

if y'all are non comfortable or confused on adding multiple JAR files into classpath, together with thus run across 5 ways to add together multiple JAR to Classpath inward Java.

That's all on How to convert JSON String to Java object using Jackson library. Though, this is a short illustration together with actual object could hold out to a greater extent than complex, it demonstrate the procedure of creating Java object from JSON String. You tin dismiss besides purpose other JSON library similar GSON instead of Jackson to convert JSON String to Java object. Full listing of JSON libraries are available on http://www.json.org/.

Further Learning
Master Java Web Services together with REST API alongside Spring Boot
REST API Design, Development & Management
tutorial)
  • 3 Ways to parse JSON String inward Java? (tutorial)
  • How to convert JSON array to String array inward Java? (example)
  • How to convert a Map to JSON inward Java? (tutorial)
  • How to purpose Google Protocol Buffer inward Java? (tutorial)
  • How to purpose Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST together with RESTful Web Services (books)


  • P.S. - If y'all desire to acquire how to railroad train RESTful Web Services using Spring Framework, banking concern fit out Eugen Paraschiv's REST alongside Spring course. He has latterly launched the certification version of the course, which is sum of exercises together with examples to farther cement the existent basis concepts y'all volition acquire from the course.

    0 Response to "How To Convert Json String To Coffee Object - Jackson Example"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel