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);
}
}How it works
Count the classes ObjectSerialization and Configuration and the function toString as the entire surface area of Object Serialization with JSON.
Putting it to use
Signature: public String toString()
Running the file prints labeled results such as Deserialized:, Serialized: — each operation’s effect is visible in the output.
Core lines
return appName + " (max=" + maxConnections + ", features=" + features + ")";
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
FAQ
- What does Object Serialization with JSON print when run?
- No setup needed: run the file and look for labeled lines like `Deserialized:`, `Serialized:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.