Object Serialization with JSON

Demonstrates serializing and deserializing objects to JSON format, showing how to persist and transfer structured data between application components.

JavaConfig Management

Code

javasnippet
54 lines
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

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.