DEV Community

Mercy
Mercy

Posted on

How can one parse JSON text in a Java application?

Sending some data from the server to the client, so that the data can be displayed on a web page or vsv, requires JSON. Share in the comments what you use JSON for.

What happens when you do not use JSON.

New files you write can't be read by the previous version and the files you already have can't be read by the new version. With JSON the previous version just ignores the items it doesn't know about and the new version can use a default for the missing fields. You can do that with binary as well but then you have to keep both the new and old read/write functions and embed a version number in the file, so using JSON is always best. "What do you all think is the advantage of using text-based-formats?".

What is JSON

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.

Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON. Here today we are emphasising How it can be used in JAVA?

Parsing JSON text in a Java application can be done using libraries such as Jackson, Gson, or org.json. Today we are looking at each one of the libraries one by one.

We start by demonstrating how we can use Jackson (FasterXML)

Jackson allows parsing JSON into Java objects or Map. You can start by adding dependencies to the pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>
Enter fullscreen mode Exit fullscreen mode

Code:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParserExample {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\": \"John\", \"age\": 30}";

        // Parse JSON into a Java object
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);

        // Print parsed object
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

class Person {
    private String name;
    private int age;

    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
Enter fullscreen mode Exit fullscreen mode

From the above code, we are converting JSON to Java object:

Person person = objectMapper.readValue(json, Person.class);

  • The readValue method parses the JSON string (json) and maps it to the specified Java class (Person).
  • Jackson matches the JSON fields (name and age) to the fields in the Person class by name.
  • Jackson uses the default constructor of the Person class and the setter methods (setName and setAge) to populate the object's fields.
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
Enter fullscreen mode Exit fullscreen mode
  • The getName and getAge methods are used to retrieve the values from the Person object.
  • The values parsed from the JSON string (John and 30) are printed.

The person class

class Person {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
Enter fullscreen mode Exit fullscreen mode
  • ThePerson class defines the structure of the object Jackson will map to.
  • It contains private fields (name and age) and public getter and setter methods, following the **JavaBean **convention.

From the above, we learn that the parsed object allows working with the JSON data as a strongly-typed Java object.

2. Using Gson

Gson is a JSON library developed by Google. To use it add the dependencies to the pom.xml as I did in the above example.

import com.google.gson.Gson;

public class JsonParserExample {
    public static void main(String[] args) {
        String json = "{\"name\": \"John\", \"age\": 30}";

        // Parse JSON into a Java object
        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);

        // Print parsed object
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

class Person {
    private String name;
    private int age;

    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
Enter fullscreen mode Exit fullscreen mode
  • The fromJson method of Gson is used to parse the JSON string (json) and convert it into an instance of the Person class.

How it works:

  • Gson matches the keys in the JSON string (name and age) to the fields in the Person class.
  • The matching is case-sensitive and relies on the naming of the fields.
  • Gson uses the default constructor of the Person class and the private fields name and age are populated internally.

Notice the difference in their parsing of JSON into JAVA objects.
For Jackson:

 // Parse JSON into a Java object
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);
Enter fullscreen mode Exit fullscreen mode

For Gson:

  Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);
Enter fullscreen mode Exit fullscreen mode

and For org.Json

 // Parse JSON into JSONObject
        JSONObject jsonObject = new JSONObject(json);
Enter fullscreen mode Exit fullscreen mode
import org.json.JSONObject;

public class JsonParserExample {
    public static void main(String[] args) {
        String json = "{\"name\": \"John\", \"age\": 30}";

        // Parse JSON into JSONObject
        JSONObject jsonObject = new JSONObject(json);

        // Access values
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Choose the library that best suits your project's requirements. I always use Jackson for most enterprise projects, I love it because of its performance and features. What are other Libraries or methods that you feel are left out from the article? Add them in the comments 👇

Top comments (0)