// pom.xml: com.fasterxml.jackson.core:jackson-databind
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.List;
class Demo {
static final ObjectMapper MAPPER = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT); // pretty-print
record User(int id, String name, String email) {}
public static void main(String[] args) throws Exception {
// Object → JSON
var user = new User(42, "Alice", "a@x.com");
String json = MAPPER.writeValueAsString(user);
System.out.println(json);
// {
// "id" : 42,
// "name" : "Alice",
// "email" : "a@x.com"
// }
// JSON → Object
String input = """
{"id": 7, "name": "Bob", "email": "b@x.com"}
""";
User parsed = MAPPER.readValue(input, User.class);
System.out.println(parsed);
// Generic types via TypeReference
String arr = "[{\"id\":1,\"name\":\"a\"},{\"id\":2,\"name\":\"b\"}]";
var users = MAPPER.readValue(arr,
new com.fasterxml.jackson.core.type.TypeReference<List<User>>() {});
System.out.println(users);
}
}
Create a free account and build your private vault. Share publicly whenever you want.