← All articles
Backend1 min read

Serialization in Java Done Right

Java's built-in serialization is a security and compatibility minefield. Prefer explicit formats like JSON and treat native serialization with caution.

S

Swapnika Voora

Author

Native Java serialization is convenient but couples your wire format to class internals and has a long history of deserialization vulnerabilities. For most systems, an explicit text format is the safer default.

Prefer explicit formats

Serialize to JSON with a library like Jackson so the format is stable, inspectable, and language-neutral.

Json.java
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(order);
Order restored = mapper.readValue(json, Order.class);

If you must use native serialization

Guard against untrusted input with a serialization filter that whitelists allowed classes.

Filter.java
var filter = ObjectInputFilter.Config.createFilter("com.acme.*;!*");
ObjectInputFilter.Config.setSerialFilter(filter);

Takeaways

  • Never deserialize untrusted native Java bytes without a strict filter.
  • Prefer JSON, Protobuf, or Avro for anything crossing a boundary.
  • Version your DTOs so old messages keep deserializing after schema changes.

Mark truly transient fields with transient and give classes an explicit serialVersionUID if you do use Serializable.

#java#serialization#security

More in Backend