- How can we convert a JSON string to a JSON object in Java?
- Example 1
- Output
- Example 2
- How to parse a JSON String into an object with Java
- Parse JSON in Java using the Gson library
- Parse JSON in Java using the Jackson library
- Parse JSON in Java using the JSON-java library
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- Convert String to JSON Object in Java
- Use JSONObject to Convert a String to JSON Object in Java
- Use Google Gson to Convert a String to JSON Object in Java
- Use Jackson to Convert a String to JSON Object
- Related Article — Java String
- Related Article — Java JSON
- How to Parse JSON in Java
- Parse JSON Using org.json
- Parse JSON Using Gson
- Parse JSON Using JsonPATH
How can we convert a JSON string to a JSON object in Java?
The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data.
The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization.
In the below two examples, We can convert a JSON string to a JSON object.
Example 1
import org.json.JSONObject; import org.json.JSONArray; public class StringToJSONTest < public static void main(String args[]) < String str = "[,, ]"; JSONArray array = new JSONArray(str); for(int i=0; i < array.length(); i++) < JSONObject object = array.getJSONObject(i); System.out.println(object.getString("No")); System.out.println(object.getString("Name")); >> >
Output
Example 2
import org.json.*; public class StringToJsonObjectTest < public static void main(String[] args) < String str = ""; JSONObject json = new JSONObject(str); System.out.println(json.toString()); String tech = json.getString("technology"); System.out.println(tech); > >
How to parse a JSON String into an object with Java
The JSON format is one of the most used data format for storing and exchanging information using computers.
Although you can parse a JSON string as a JSON object without these libraries, it’s generally not recommended unless you are prepared to put in the required effort.
Without using third-party libraries, you need to implement the JSON parser specification according to the ECMA International specification that you can find here.
You need to test the parser library you’ve created and then be prepared to maintain and improve that library. You also need to write code that can handle the wrong JSON string format well or you might produce the wrong output.
In short, it’s better to use a tried-and-tested JSON library for Java that has been developed by many developers and is mature enough to handle many use cases.
This tutorial will help you learn how to parse JSON strings into objects and vice versa using the three libraries mentioned above.
Let’s start with the Gson library.
Parse JSON in Java using the Gson library
The Gson library is a Java library used to convert Java objects into their JSON representation and vice versa.
One notable feature of the Gson library is the full support for Java generics.
Once you add the library as a dependency to your Java project, you can use the fromJson() method to convert a string into a Java object.
For example, suppose you have a Java class named Person with the following definitions:
You can parse a string as an instance of the Person class as follows:
You can convert the object back into a String with the toJson() method of the Gson library as shown below:
And that’s how easy it is to parse a JSON string into a Java object using Gson.
You can find more detailed information about the library on the Gson Github page
Parse JSON in Java using the Jackson library
The Jackson library is a data-processing tool for Java that can process not only JSON data format, but also others like CSV, TOML, YAML, or XML.
Still, Jackson became popular among Java and Android developers because of its ability to parse streaming JSON data.
To parse a JSON string into a Java object with Jackson, you need to create a class with setters and getters for its fields as shown below:
Without the setters and getters, Jackson will have no access to the Person class fields
The code below shows how to parse a string into a JSON object using Jackson:
""" First, you need to create an instance of the ObjectMapper class from Jackson. The instance is named mapper in the above code.
Next, you need to call the readValue() method from the mapper instance, passing the String variable as the first argument and the Java blueprint class as the second argument.
To parse a Java object into a JSON string, you need to call the writeValueAsString() method from the mapper instance as follows:
And that’s how you can parse a JSON string as a Java object using the Jackson library.
For advanced use and other Jackson add-on libraries, you can visit the Jackson Github page.
Parse JSON in Java using the JSON-java library
The JSON-java library is a lightweight Java library that can be used to parse a JSON string into a Java object and vice versa.
The library is doesn’t require you to pass a Java class as the JSON object blueprint.
Instead of your defined class instance, the object will be of the JSONObject instance.
The code below shows how you can use the JSON-java library to create an object from a JSON string:
To convert the JSONObject back into a String , you can call the toString() method from the instance as follows:
The JSONObject implementation is similar to the Java HashMap class, so the order of the key-value pairs won’t be preserved.
This is why the string output of the toString() method above is not in the same order as the original jsonStr variable.
And that’s how you can parse a JSON string using the JSON-java library.
For more information, you can visit the JSON-java Github page.
Now you’ve learned how to parse JSON string using Java with the three most popular JSON libraries. Well done! 👍
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Convert String to JSON Object in Java
- Use JSONObject to Convert a String to JSON Object in Java
- Use Google Gson to Convert a String to JSON Object in Java
- Use Jackson to Convert a String to JSON Object
In this tutorial, we are going to discuss how to convert a string into a JSON object in Java. We have different libraries available to perform this task.
Use JSONObject to Convert a String to JSON Object in Java
JSONObject can parse a string into a map-like object. It stores unordered key-value pairs. JSON-java library, commonly known as org.json , is used here with required maven dependency. The maven dependency which we used is given below.
org.json json 20201115
To parse a JSON string to JSONObject , we pass the string to the constructor as shown below.
import org.json.JSONObject; import org.json.JSONException; public class StringToJsonObject public static void main(String[] args) try String str = ""; JSONObject jsonObject = new JSONObject(str); System.out.println("OBJECT : "+jsonObject.toString()); > catch (JSONException err) System.out.println("Exception : "+err.toString()); > > >
Use Google Gson to Convert a String to JSON Object in Java
Google Gson is a java library to serialize/deserialize Java Objects to JSON or vice-versa. It can also be used to convert Java string to its equivalent JSON Object.
The maven dependency that is required for this library is given below.
com.google.code.gson gson 2.8.6
In this code, we first create an instance of Gson using GsonBuilder by calling its create() method. We can also enable various configuration settings on builder . As shown below we use its setPrettyPrinting() method. As the name suggests it pretty prints the JSON output.
Later we used the fromJson method of Gson Object, which parses the JSON string to the User object. The toJson() method uses Gson to convert the User object back to the JSON string. Thus string str is converted into a JSON Object using the Gson library.
import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; import com.google.gson.Gson; public class StringToJsonObject public static void main(String[] args) try String str = ""; GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); User user = gson.fromJson(str,User.class); System.out.println(user.ShowAsString()); str= gson.toJson(user); System.out.println("User Object as string : "+str); >catch(JsonIOException err) System.out.println("Exception : "+err.toString()); > > > class User public String name; public int age; public String place; public String ShowAsString() return "User ["+name+", "+ age+ ", " +place+ "]"; > >
User [John, 21, Nevada] User Object as string : "name": "John", "age": 21, "place": "Nevada" >
Use Jackson to Convert a String to JSON Object
Jackson is also known as the Java JSON library. The ObjectMapper is used to map JSON into Java Objects or Java Objects into JSON. The maven dependency used for this library is shown below.
com.fasterxml.jackson.core jackson-databind 2.11.3
The Jackson has a built-in tree model to represent JSON Object. JsonNode is the class that represents the tree model. The ObjectMapper instance mapper parses JSON into a JsonNode tree model calling readTree() .
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class StringToJsonObject public static void main(String[] args) String json_str = ""; ObjectMapper mapper = new ObjectMapper(); try JsonNode node = mapper.readTree(json_str); String name = node.get("name").asText(); String place = node.get("age").asText(); System.out.println("node"+node); System.out.println("name: "+name +", place: "+place); > catch (JsonProcessingException e) e.printStackTrace(); > > >
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java String
Related Article — Java JSON
Copyright © 2023. All right reserved
How to Parse JSON in Java
In this tutorial we will look at how to parse JSON in Java using different libraries.
JSON stands for JavaScript Object Notation, and it is based on a subset of JavaScript.
As a data-exchange format, it is widely used in web programming. Here we show how to parse JSON in Java using the org.json library.
A JSON object is an unordered set of key/value pairs. A JSON array is an ordered collection of values. The values themselves could be objects or arrays.
We will be parsing this JSON as an example to retrieve values for pageName , pagePic and post_id
Parse JSON Using org.json
To use org.json to parse JSON in Java, you need to add the library as a dependency. This can be fetched from Maven repository
import org.json.JSONArray; import org.json.JSONObject; public class ParseJSON < static String json = ". "; public static void main(String[] args) < JSONObject obj = new JSONObject(json); String pageName = obj.getJSONObject("pageInfo").getString("pageName"); System.out.println(pageName); JSONArray arr = obj.getJSONArray("posts"); for (int i = 0; i < arr.length(); i++) < String post_id = arr.getJSONObject(i).getString("post_id"); System.out.println(post_id); >> >
N.B. the . needs to be replaced by the JSON string. This has been omitted from the code above for clarity.
First, we need to convert the JSON string into a JSON Object, using JSONObject class.
Also, note that “pageInfo” is a JSON Object, so we use the getJSONObject method.
Likewise, “posts” is a JSON Array, so we need to use the getJSONArray method.
Parse JSON Using Gson
In order to use Gson to parse JSON in Java, you need to add the library as a dependency. You can get the latest version from Maven repository
The below example shows how to Parse the above JSON with Gson.
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ParseJSON < static String json = ". "; public static void main(String[] args) < JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString(); System.out.println(pageName); JsonArray arr = jsonObject.getAsJsonArray("posts"); for (int i = 0; i < arr.size(); i++) < String post_id = arr.get(i).getAsJsonObject().get("post_id").getAsString(); System.out.println(post_id); >> >
Like the previous example, the . needs to be replaced by the JSON string.
Parse JSON Using JsonPATH
The above two examples require a full deserialization of the JSON into a Java object before accessing the value in the property of interest. Another alternative, which does not go this route is to use JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
Like before, you need to add JsonPATH as a dependency, which can be fetched from Maven repository
For example, to parse the above JSON we can use:
import com.jayway.jsonpath.JsonPath; public class ParseJSON < static String json = ". "; public static void main(String[] args) < String pageName = JsonPath.read(json, "$.pageInfo.pageName"); System.out.println(pageName); Integer posts = JsonPath.read(json, "$.posts.length()"); for(int i=0; i < posts; i++) < String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id"); System.out.println(post_id); >> >