All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Convert String To JSONobject Java

Last Updated : Mar 11, 2024

Convert String To JSONobject Java

In this article we will show you the solution of Convert string to jsonobject java, working with JSON data in Java applications is a regular activity. A popular lightweight data interchange format for transferring data between systems and languages is JSON (JavaScript Object Notation).

It is frequently necessary when working with JSON to translate a stringrepresentation of the data into a Java object for further processing.

Java's parsing of JSON strings results in the creation of related JSONObject instances that represent the JSON structure when converting a string to a JSONObject.

For easy parsing and manipulation of JSON data, popular libraries like Jackson, Gson, and JSON.simple provide the JSONObject class.

Three steps are normally required to convert a string to a JSONObject: first, parse the JSON string using a parser you write yourself or one given by a library; second, extract the values you want from the parsed JSON; and third, create a JSONObject instance to hold the values you extracted.

We'll talk about the converted string to jsonobject in Java concept now.

Step By Step Guide On Convert String To JSONobject Java :-

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class StringToJSONObjectExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Magan\", \"age\":30, \"city\":\"New York\"}";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            ObjectNode jsonObject = objectMapper.createObjectNode();
            convertJsonNodeToJsonObject(jsonNode, jsonObject);
            System.out.println(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void convertJsonNodeToJsonObject(JsonNode jsonNode, ObjectNode jsonObject) {
        for (JsonNode field : jsonNode) {
            String fieldName = field.fieldNames().next();
            JsonNode fieldValue = field.get(fieldName);
            if (fieldValue.isObject()) {
                ObjectNode nestedObject = jsonObject.putObject(fieldName);
                convertJsonNodeToJsonObject(fieldValue, nestedObject);
            } else {
                jsonObject.set(fieldName, fieldValue);
            }
        }
    }
}
  1. You can see that we wrote the Java code to convert a string to a JSON object in this place.
  2. To get the relevant classes from the Jackson library, we include the imports that are required.
  3. The class StringToJSONObjectExample is intended to serve as the program's entry point.
  4. We create a JSON string and apply it to the jsonString variable inside the main method.
  5. The name, age, and city fields of the object represented by this JSON string are all present.
  6. The ObjectMapper instance objectMapper is created. Jackson's ObjectMapper class is in charge of processing and mapping JSON data.
  7. The JSON string is parsed into a JsonNode object called jsonNode using the ObjectMapper's readTree function.
  8. To hold the transformed JSON object, we build an empty ObjectNode called jsonObject.
  9. To turn the jsonNode into a JSONObject, we invoke the convertJsonNodeToJsonObject function. This function iterates through the fields in the jsonNode and takes the jsonNode and jsonObject as inputs.
  10. We use a foreach loop to repeatedly traverse through the fields of the jsonNode inside the convertJsonNodeToJsonObject function. Each field in the jsonNode is represented by the field variable.
  11. Using field.fieldNames(), we can retrieve the field name.and save it in the fieldName variable using next().
  12. Using field, we can get the value of the field.fieldValue should be set to the value returned by get(fieldName).
  13. Using fieldValue, we determine the type of the field value.isObject().
  14. If yes, we use jsonObject to build a new ObjectNode called nestedObject and add it to the jsonObject.putObject(fieldName).
  15. The nested object is then converted by repeatedly invoking the convertJsonNodeToJsonObject function.
  16. If the field value is a primitive value (a text, number, boolean, etc.), it is not an object.
  17. In this instance, we use the jsonObject.set(fieldName, fieldValue) method to add the field to the object.
  18. We print the transformed jsonObject to the console using System.out after iterating through each field in the jsonNode.println(jsonObject.toString()).
  19. To handle any exceptions that might come up while processing or converting JSON, we offer exception handling.
  20. If an exception occurs, we use e.printStackTrace() to print the stack trace to the console.

Conclusion :-

As a result, we have successfully mastered the Java notion of string to JSON object conversion.

Using the ObjectMapper class, we also discovered how to parse the JSON string into a JsonNode and then recursively traverse through its properties to create a JSONObject.

We can manage nested objects with this method, and we can extract both simple and complex values.

I hope this article on Convert string to jsonobject java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪