Monday, September 16, 2024

How to convert JSON String to Java object - Jackson Example

JSON stands for JavaScript object notation, is a lightweight text or string representation of an object and quickly becoming a popular data exchange format. Though it's pretty early to say that JSON is going to replace XML as a popular data interchange format, It is certainly providing an alternative. JSON represents data in two formats either an object or an array. The JSON object is an unordered collection of keys and values, similar to the String representation of the hash table. On the other hand, JSON Array is an ordered collection of values.

The main difference between  JSON Object and  JSON array is their representation. The JSON object is started with left-brace { and ends with right brace } and key values are separated using a colon (:).

On the other hand, JSON Array starts with the left bracket [ and ends with the right bracket ] and each value is separated by a comma. By looking at structure, You can write your JSON parser to parse JSON object or array to Java object, but you don't need to. 

There is a lot of open-source library in Java which provides tried and tested way of converting JSON String to Java object e.g. Jackson and GSON. In this Java tutorial, we will see an example of converting a JSON String to a Java object using the Jackson library






How to convert JSON String to Java object using Jackson

JSON String to Java Object Conversion Example using Jackson libraryIt's very easy to create Java objects from JSON String using the Jackson library. It's literally requires two lines of code to do this, as shown in the following Java example. If you look at code, most of the code is for creating Java class e.g. User in this case, while code required to convert JSON String to Java object is just two lines in fromJson(String json) method. 



This method takes a Json String which represents a User object in JSON format and converts it into a Java User object. In this Java example, I have created User as a 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 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=" + 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": "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 can either use Jackson or Gson to convert JSON String to Java object and in this Java tutorial we have used Jackson library for JSON to Java object conversion. If you are using Maven for dependency management than you can add following dependency in POM.xml :

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

Or you can simply add the following 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 you are not comfortable or confused about adding multiple JAR files into the classpath, then see 5 ways to add multiple JAR to Classpath in Java.


That's all on How to convert JSON String to Java object using Jackson library. Though this is a trivial example and the actual object could be more complex, it demonstrates the process of creating Java objects from JSON String. 

You can also use other JSON libraries like GSON instead of Jackson to convert JSON String to Java objects. A full list of JSON libraries is available on http://www.json.org/.


Other JSON tutorials you may like to explore
  • How to convert a JSON  String to POJO in Java? (tutorial)
  • 3 Ways to parse JSON String in Java? (tutorial)
  • How to convert JSON array to String array in Java? (example)
  • How to convert a Map to JSON in Java? (tutorial)
  • How to use Google Protocol Buffer in Java? (tutorial)
  • How to use Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST and RESTful Web Services (books)

P.S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out this Spring and REST web services courses from Eugen and others. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real-world concepts you will learn from the course.

5 comments :

Eliot Pearson said...

Very solid example you have here. I would stick with Jackson even though you could use either that or Gson. Jackson performs better.

Unknown said...

Thnx for this Tutorial,
In my case I am using JSON. Whenever I use ObjectClass obj = new Gson().fromJson(JsonString, ObjectClass .class) throws my an Exception com.google.gson.stream.malformedJsonException: JSOn forbids ocal reflixes..
I Generated a class ObjectClass with attributes, and aslo specified with the SpecializedName. but nothing helps..
and idea??

Utkarsh Thakkar said...

Thanks for the tutorial. Can you please suggest me any way to create a list from json string? I am getting a list of Objects in json string.

Anonymous said...

I'm new in android, plese helf me how can I see result of this programm? I run it and see nothing

Unknown said...

Thanks, good tutorial, easy to understand.
Once again Thank U.

Post a Comment