3 ways to convert String to JSON object in Java?

It's very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn't yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open-source libraries which allows you to create JSON object from JSON formatted String e.g. Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step by step examples.

Even though you can use a simple or complex JSON String like with lots of attributes and JSON arrays, I'll use following JSON String for example purpose:

jsonString = {
  "name" : "Ronaldo",
  "sport" : "soccer",
  "age" : 25,
  "id" : 121,
  "lastScores" : [ 2, 1, 3, 5, 0, 0, 1, 1 ]
}

It's simple, has 5 attributes, two of which are String and the other two are numeric. One attribute, lastScore is a JSON array.




String to JSON Object using Gson

The Gson is an open-source library to deal with JSON in Java programs. It comes from none other than Google, which is also behind Guava, a common purpose library for Java programmers. You can convert JSON String to Java object in just 2 lines by using Gson as shown below :

Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)

You can also convert a Java object to JSON by using toJson() method as shown below

String str = g.toJson(p);

The good thing about Gson is that it's feature-rich and comes from Google, which is known for performance. Btw, if you are not very familiar with JSON format itself, I would suggest joining Introduction to JSON on Udemy to learn more. It's a must that you know some basics of JSON before encoding and decoding Java objects to JSON.




JSON String to Java object using JSON-Simple

The JSON-Simple is another open-source library which supports JSON parsing and formatting. The good thing about this library is its small size, which is perfect for memory constraint environments like J2ME and Android.

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

The good thing about json-simple is that it is also JDK 1.2 compatible, which means you can use it on a legacy project which is not yet in Java 5.

3 ways to convert String to JSON object in Java?


String to JSON - Jackson Example

Jackson is I guess the most popular JSON parsing library in Java world. It's fast, feature-rich and supports streaming which is great for parsing large JSON output from web services. Following one-liner convert JSON string representing a soccer player into a Java class representing player:

Player ronaldo = new ObjectMapper().readValue(jsonString, Player.class);

One of the drawbacks of Jackson is that it requires JDK 1.5 so if you are stuck in earlier Java version than it may not fit there. Also, Jackson doesn't support J2ME, but one of the main advantages of using Jackson is that it supports streaming which can be used to parse huge JSON response without loading it fully in memory.

Jackson is a very popular and efficient Java library to map Java object to JSON and vice-versa. If you want to learn the basics of the Jackson library and how to use them, I suggest you take a look at the Java: JSON Databinding with Jackson course on Pluralsight. One of the best course to learn Jackson API for Java developers.


best course to learn Jackson API for Java developers

Btw, you would need a Pluralsight membership to get access this course, which cost around $29 per month or $299 annually (14% discount).

If you don't have Pluralsight membership, I encourage you to get one because it gives you access to their 5000+ online courses on all the latest topics like front-end and back-end development, machine learning, etc. It also includes interactive quizzes, exercises, and the latest certification material.

Alternatively, you can also sign up for their 10-day free trial, which provides 200 minutes of watch time to any course. You can use that time to access this course free.

If you like books, you can also read more about how to parse JSON String to Java object using these libraries on Developing RESTful Services with JSON, one of the good books which explain how to use consume JSON data from web services.


That's all about how to convert String to JSON object in Java. You can use any of the json-simple, Gson or Jackson for parsing JSON messages received from web services, each of them has their own advantage. Json-simple has a small memory footprint means it's quite suitable for J2ME and Android client, while Jackson is feature-rich so better supported for a large project. Gson is in between them and my favorite general-purpose JSON parser in Java programs.

Further Learning
Master Java Web Services and REST API with Spring Boot
REST API Design, Development & Management
Java Web Fundamentals


Other JSON tutorials for Java programmers
  • 5 JSON libraries Java JEE Programmer should know (list)
  • How to parse JSON to/from Java Object using Jackson? (tutorial)
  • How to convert JSON array to String array in Java using Gson? (tutorial)
  • How to parse a large JSON file using Jackson Streaming API? (example)
  • How to use Google Protocol Buffer (protobuf) in Java? (tutorial)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the purpose of different HTTP methods in REST? (see here)
  •  How to convert JSON to HashMap in Java? (guide)
  • 10 Things Java developer should learn in 2019?  (article)
  • How to ignore unknown properties while parsing JSON in Java? (tutorial)
  • How to parse JSON with date fields in Java? (example)
  • 5 Courses to learn RESTful  API and Web services in Java? (courses)
  • 10 free courses to learn Java in-depth (resource)

Thanks for reading this article so far. If you like these 3 ways to convert String to JSON object in Java, then please share with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If are a complete beginner about JSON (JavaScript Object Notation) I strongly suggest you go through Introduction to JSON course on Udemy to understand the structure and properties of JSON. This will help you a lot while dealing with JSON output, formating them and producing them from your own API.

23 comments:

  1. Thank you for the examples. Nice post. Can you please also tell which library gives best performance? Also, which library supports a lenient conversion? What I mean by lenient is, an attribute is defined in json but not in the java class, and vice versa ;still gets successfully converted
    Thanks
    Abhijeet

    ReplyDelete
  2. Where is Player class? It would be clear if you could show/comment that. Thanks.
    PS:I am new to all this. Thanks

    ReplyDelete
    Replies
    1. Hi Green,
      Player is a Bean/Pojo class containing Java Objects based on which JSON to JavaObjects [and vice versa] takes place.

      This class will contain all the headers/root objects for your JSON.
      JSON for Players:
      {"NAME":"AD","ID":0001}
      Java Class for Players:
      {
      String NAME;
      int ID;
      ----set getters and setters for these variables
      }
      Hope this helps.

      Delete
  3. What if you don't want to convert to a class (e.g. Player) but just want it in a JSON format to be able to parse parts of it?

    ReplyDelete
  4. What Anonymous said on March 29, 2017 at 1:19 PM

    ReplyDelete
  5. Nice article, but the Spring default jackson is not validating the JSON data properly - http://stackoverflow.com/questions/44033574/spring-rest-mvc-jackson-not-validating-input-json-data-properly?noredirect=1#comment75094311_44033574

    ReplyDelete
  6. What's the Player class all about?

    ReplyDelete
  7. how to get JSONObject value to string object and that value how to set on setter value to db.
    please provide for solution

    ReplyDelete
  8. How to create interface to convert string to Json()?

    ReplyDelete
  9. [[Ljava.lang.Object;@c2ac0e4, [Ljava.lang.Object;@21390bd8, [Ljava.lang.Object;@17206755, [Ljava.lang.Object;@26ea189d, [Ljava.lang.Object;@7c9dc144, [Ljava.lang.Object;@159372c4, [Ljava.lang.Object;@19db5ec, [Ljava.lang.Object;@77457bb2, [Ljava.lang.Object;@65c003ff, [Ljava.lang.Object;@6bcb58d1, [Ljava.lang.Object;@795b291, [Ljava.lang.Object;@5b51c13a, [Ljava.lang.Object;@3eebee54, [Ljava.lang.Object;@fd73488]
    how to convert java code

    ReplyDelete
  10. Hi,
    i have a interesting Jason String and i coud not to pars it because looks different.
    i just need to take a Status and message as Object can somebody help me?

    {“certInfo”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”vulnerabilities”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”serverConfig”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}}}

    ReplyDelete
  11. how to convert string to json object in jsp

    ReplyDelete
    Replies
    1. Just like shown here, in JSP you can put Jackson or Gson library in the WEB-INF/lib and then write code in scriptlet but better if you do this conversion in Servlet as JSP is just meant for displaying data not generating.

      Delete
  12. I cannot relate this.

    I am new to JAVA, i have a String which has a JSON in it.

    I am trying to create a JSON object.

    I cannot understand the Players here and how i can use that inorder for me to create JSON object.

    Any help is appreciated.

    ReplyDelete
    Replies
    1. Can you explain your requirement in detail, that will help. You are saying you are trying to create JSON object, so it looks like you want to convert a Java object into JSON String right? If you are using Gson, you can use toJson() method as shown above. May be posting your code here would help

      Delete
  13. Since Java EE 8 (2017) JSON should be processed by JSON-B 1.0 and JSON-P 1.1. Yasson is the reference implementation. Jackson, Gson etc. are subsumed in this standard and they contributed to it.

    ReplyDelete
  14. which package and dependency to use for JSONParser and JSONObject

    ReplyDelete
  15. Hello Aishwarya, you need to use json-simple-1.1.1.jar to use JSONParser and JSONObject, you can download the JAR file from Maven repository https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1. If you are using Maven, Gradle or Ivy then you can also include it as dependency.

    ReplyDelete
  16. I am using ObjectMapper().readValue(json, SomeClass.class) to convert json to Object.

    My json contains double value as 44702217.67. But after json is mapped to Object, this double value gets converted as 4.470221767E7. Is there any way to prevent this?

    ReplyDelete
  17. Alagu RajaNovember 3, 2017 at 5:26 AM
    how to get JSONObject value to string object and that value how to set on setter value to db.
    please provide for solution
    Reply

    AnonymousDecember 17, 2017 at 8:16 PM
    How to create interface to convert string to Json()?

    Reply

    UnknownJuly 12, 2018 at 4:01 AM
    [[Ljava.lang.Object;@c2ac0e4, [Ljava.lang.Object;@21390bd8, [Ljava.lang.Object;@17206755, [Ljava.lang.Object;@26ea189d, [Ljava.lang.Object;@7c9dc144, [Ljava.lang.Object;@159372c4, [Ljava.lang.Object;@19db5ec, [Ljava.lang.Object;@77457bb2, [Ljava.lang.Object;@65c003ff, [Ljava.lang.Object;@6bcb58d1, [Ljava.lang.Object;@795b291, [Ljava.lang.Object;@5b51c13a, [Ljava.lang.Object;@3eebee54, [Ljava.lang.Object;@fd73488]
    how to convert java code

    Reply

    UnknownJuly 12, 2018 at 4:02 AM
    how i convert java side

    Reply

    ArdalanDecember 4, 2018 at 2:12 AM
    Hi,
    i have a interesting Jason String and i coud not to pars it because looks different.
    i just need to take a Status and message as Object can somebody help me?

    {“certInfo”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”vulnerabilities”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”serverConfig”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}}}

    Reply

    AnonymousJanuary 16, 2019 at 1:17 AM
    how to convert string to json object in jsp

    Reply
    Replies

    Javin PaulJanuary 16, 2019 at 5:17 AM
    Just like shown here, in JSP you can put Jackson or Gson library in the WEB-INF/lib and then write code in scriptlet but better if you do this conversion in Servlet as JSP is just meant for displaying data not generating.

    Reply

    RoyJanuary 21, 2019 at 4:45 PM
    I cannot relate this.

    I am new to JAVA, i have a String which has a JSON in it.

    I am trying to create a JSON object.

    I cannot understand the Players here and how i can use that inorder for me to create JSON object.

    Any help is appreciated.

    Reply
    Replies

    Javin PaulJanuary 22, 2019 at 4:46 AM
    Can you explain your requirement in detail, that will help. You are saying you are trying to create JSON object, so it looks like you want to convert a Java object into JSON String right? If you are using Gson, you can use toJson() method as shown above. May be posting your code here would help

    Reply

    Marc DzaebelMarch 1, 2019 at 10:34 AM
    Since Java EE 8 (2017) JSON should be processed by JSON-B 1.0 and JSON-P 1.1. Yasson is the reference implementation. Jackson, Gson etc. are subsumed in this standard and they contributed to it.

    Reply

    AishwaryaApril 17, 2019 at 1:05 AM
    which package and dependency to use for JSONParser and JSONObject

    Reply

    javin paulApril 17, 2019 at 5:38 AM
    Hello Aishwarya, you need to use json-simple-1.1.1.jar to use JSONParser and JSONObject, you can download the JAR file from Maven repository https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1. If you are using Maven, Gradle or Ivy then you can also include it as dependency.

    Reply

    RahulSeptember 11, 2019 at 7:02 AM
    I am using ObjectMapper().readValue(json, SomeClass.class) to convert json to Object.

    My json contains double value as 44702217.67. But after json is mapped to Object, this double value gets converted as 4.470221767E7. Is there any way to prevent this?

    Reply

    ReplyDelete