How do you parse JSON in Java?

Introduction

  • Parsing JSON (JavaScript Object Notation) in Java is a common requirement when working with web APIs or handling structured data.

Libraries for Parsing JSON in Java

  1. Jackson (Most widely used)
  2. Gson (Lightweight and easy to use)
  3. org.json (Simple and minimalistic)

Practical Approach Using Jackson (Step-by-Step Instructions)

1. Add Dependency

If using Maven, include Jackson dependency in your pom.xml:

xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency>

2. Create Java Object

Define a Java class that maps to the structure of your JSON data.

```java

public class User {

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; }

}

```

3. Parse JSON to Java Object

Use ObjectMapper from the Jackson library to read JSON and map it to your Java object.

```java

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParser {

public static void main(String[] args) {

String json \= "{ \"name\": \"John\", \"age\": 30 }";

       ObjectMapper mapper = new ObjectMapper();
       try {
           User user = mapper.readValue(json, User.class);
           System.out.println("Name: " + user.getName());
           System.out.println("Age: " + user.getAge());
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

}

```

4. Parse JSON to Map

You can also parse JSON into a Map instead of a Java object if your JSON structure is dynamic or unknown.

```java

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JsonParser {

public static void main(String[] args) {

String json \= "{ \"name\": \"John\", \"age\": 30 }";

       ObjectMapper mapper = new ObjectMapper();
       try {
           Map<String, Object> map = mapper.readValue(json, Map.class);
           System.out.println(map);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

}

```


Conclusion

Parsing JSON in Java can be done efficiently with libraries like Jackson, Gson, or org.json. The ObjectMapper class in Jackson provides a simple way to convert JSON strings into Java objects or maps.