JSON Processing
JSON Serialization and Deserialization
JSON processing involves converting Java objects to JSON (serialization) and JSON back to Java objects (deserialization).
Jackson Library Example
Serialization (Object to JSON)
import com.fasterxml.jackson.databind.ObjectMapper;
public class User {
private String name;
private int age;
// Constructors, getters, setters
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
User user = new User("LabEx Developer", 28);
String jsonString = mapper.writeValueAsString(user);
System.out.println(jsonString);
}
}
Deserialization (JSON to Object)
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"LabEx Developer\",\"age\":28}";
User user = mapper.readValue(jsonString, User.class);
System.out.println(user.getName());
}
JSON Processing Workflow
graph LR
A[Java Object] -->|Serialization| B[JSON String]
B -->|Deserialization| A
Advanced JSON Operations
Handling Complex Objects
Operation |
Description |
Example |
Nested Objects |
Serialize/deserialize nested structures |
User with Address |
Collections |
Process lists and maps |
List of Users |
Custom Serialization |
Define custom conversion rules |
Date formatting |
JSON Streaming Processing
// Reading large JSON files efficiently
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(new File("large.json"));
while (parser.nextToken() != null) {
// Process tokens incrementally
}
Error Handling
try {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);
} catch (JsonProcessingException e) {
// Handle JSON parsing errors
System.err.println("JSON Processing Error: " + e.getMessage());
}
Best Practices
- Use try-catch for error handling
- Validate JSON before processing
- Use appropriate library for your use case
- Consider performance for large datasets
LabEx Recommended Approach
For most LabEx projects, use Jackson with proper error handling and streaming for large JSON files.