Object Serialization with JSON
Demonstrates serializing and deserializing objects to JSON format, showing how to persist and transfer structured data between application components.
Code
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.util.List;
import java.util.Map;
public class ObjectSerialization {
@JsonIgnoreProperties(ignoreUnknown = true)
static class Configuration {
@JsonProperty("app_name")
private String appName;
@JsonProperty("max_connections")
private int maxConnections;
@JsonProperty("features")
private List<String> features;
@JsonCreator
public Configuration(
@JsonProperty("app_name") String appName,
@JsonProperty("max_connections") int maxConnections,
@JsonProperty("features") List<String> features
) {
this.appName = appName;
this.maxConnections = maxConnections;
this.features = features;
}
@Override
public String toString() {
return appName + " (max=" + maxConnections + ", features=" + features + ")";
}
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = """
{
"app_name": "MyApp",
"max_connections": 100,
"features": ["auth", "logging", "cache"]
}
""";
Configuration config = mapper.readValue(json, Configuration.class);
System.out.println("Deserialized: " + config);
String output = mapper.writeValueAsString(config);
System.out.println("Serialized: " + output);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.