Java JSON Parsing: Read Data Easily

When reading JSON format data in Java, it is common to use third-party libraries like Gson or Jackson to parse the JSON string. Below is an example code using the Gson library to read JSON data.

  1. Add dependency on Gson library.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>
  1. Create a POJO class to represent the structure of JSON data.
public class Person {
    private String name;
    private int age;

    // getters and setters
}
  1. Parse JSON data using the Gson library.
import com.google.gson.Gson;

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

        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);

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

In the example above, we first created a JSON string containing “name” and “age” fields. We then used the fromJson method of the Gson library to convert the JSON string to a Person object, and printed the values of the fields.

Besides the Gson library, the Jackson library is also a popular JSON parsing library, with similar usage. You can choose the appropriate library based on your own needs to read JSON formatted data.

bannerAds