javaintermediate
Jackson — JSON Serialization and Parsing
Parse and generate JSON with Jackson: ObjectMapper, annotations, custom serializers, and streaming.
javaPress ⌘/Ctrl + Shift + C to copy
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDate;
import java.util.*;
public class JacksonDemo {
// DTO with annotations
@JsonIgnoreProperties(ignoreUnknown = true)
record User(
@JsonProperty("user_id") Long id,
String name,
@JsonFormat(pattern = "yyyy-MM-dd") LocalDate joinDate,
@JsonInclude(JsonInclude.Include.NON_NULL) String nickname
) {}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Object to JSON
User user = new User(1L, "Alice", LocalDate.of(2024, 1, 15), null);
String json = mapper.writeValueAsString(user);
System.out.println(json);
// {"user_id":1,"name":"Alice","joinDate":"2024-01-15"}
// Pretty print
String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
// JSON to Object
String input = "{\"user_id\":2,\"name\":\"Bob\",\"joinDate\":\"2024-06-01\",\"extra\":true}";
User parsed = mapper.readValue(input, User.class);
System.out.println(parsed.name()); // Bob
// JSON to List
String arrayJson = "[{\"user_id\":1,\"name\":\"A\"},{\"user_id\":2,\"name\":\"B\"}]";
List<User> users = mapper.readValue(arrayJson, new TypeReference<List<User>>() {});
// JSON to Map
Map<String, Object> map = mapper.readValue(input, new TypeReference<>() {});
System.out.println(map.get("name")); // Bob
// Convert between types
Map<String, Object> userMap = mapper.convertValue(user, new TypeReference<>() {});
}
}Use Cases
- REST API request and response serialization
- Parsing external API JSON responses
- Converting between JSON, maps, and Java objects
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javaintermediate
JSON Serialization Without Libraries
Serialize and deserialize Java objects to JSON manually with a lightweight builder-based approach.
Best for: Lightweight JSON generation without Jackson/Gson
#java#json
pythonbeginner
Fast JSON Serialisation with orjson
Use orjson for 5-10x faster JSON serialisation of large Python dicts, dataclasses, and NumPy arrays.
Best for: high-throughput serialisation
#orjson#json
pythonbeginner
DataFrame to Dict Records
Convert DataFrames to lists of dicts for API responses, JSON export, or further processing.
Best for: API serialization
#pandas#records
kotlinintermediate
Kotlinx Serialization — JSON Parsing
Serialize and deserialize JSON with kotlinx.serialization: data classes, custom serializers, and polymorphism.
Best for: API response parsing and generation
#kotlin#serialization