JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Java provides several libraries for processing JSON data, including the popular Jackson
, Gson
, and javax.json
. In this article, we will explore three practical examples of Java JSON processing to help you understand how to work with JSON data effectively.
In many applications, you need to convert Java objects into JSON format to send over a network or to store in a file. This process is known as serialization.
import com.fasterxml.jackson.databind.ObjectMapper;
public class User {
private String name;
private int age;
// Constructors, Getters, and Setters
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
public class JsonSerializationExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("Alice", 30);
String jsonString = objectMapper.writeValueAsString(user);
System.out.println(jsonString);
}
}
Ensure you have the Jackson dependency in your pom.xml
(if using Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
When receiving JSON data, it is often necessary to convert this data back into Java objects. This process is called deserialization.
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonDeserializationExample {
public static void main(String[] args) throws Exception {
String jsonString = "{\"name\":\"Bob\", \"age\":25}";
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(jsonString, User.class);
System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
}
}
User
class.In real-world applications, you often work with collections of objects. This example demonstrates how to convert a list of Java objects to a JSON array.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class JsonListExample {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
List<User> users = new ArrayList<>();
users.add(new User("Alice", 30));
users.add(new User("Bob", 25));
String jsonArray = objectMapper.writeValueAsString(users);
System.out.println(jsonArray);
}
}
List
of User
objects into a JSON array.By understanding these examples of Java JSON processing, you can effectively manage JSON data in your Java applications.