Different serialization strategies for different formats?

Tagir Valeev amaembo at gmail.com
Thu Jun 20 09:18:02 UTC 2019


Consider we have a Color class which represents a color in RGB format:

class Color { private final int rgb; }

The most obvious and efficient way to serialize/deserialize its state is to
extract this int field:

class Color {
  private final int rgb;

  public Color(int rgb) {
    if (rgb < 0 || rgb > 0xFFFFFF) throw new IllegalArgumentException();
    this.rgb = rgb;

  public int toRGB() {return this.rgb;}

It's great for binary serialization. However if I serialize to JSON I would
not like to see `color: 16711680`. JSON or XML are intended to be at least
partially human-readable. So probably I want to see `color: red` or at
least `color: #FF0000`. Well no problem, we can alternatively serialize as

    public String toString() {
        var name = colorToName.get(this);
        return name == null ? String.format("#%06X", rgb) : name;

    public static Color parse(String str) {
        var color = nameToColor.get(str);
        if (color != null) return color;
        if (str.startsWith("#")) return new
Color(Integer.valueOf(str.substring(1), 16));
        throw new IllegalArgumentException();

    private static final Map<String, Color> nameToColor = Map.of(
            "black", new Color(0x000000),
            "red", new Color(0xFF0000),
            "green", new Color(0x00FF00),
            "blue", new Color(0x0000FF)
            // ...

    private static final Map<Color, String> colorToName =

The problem is to indicate that we provide two alternative ways to
serialize the object, and one of them (producing int) is better suitable
for binary formats while another one (producing String) is better suitable
for human-readable formats. Note that it's orthogonal to the serialization
versions: we may also have several versions of both binary and
human-readable serializers.

What do you think? Should new Java serialization support several
serialization kinds and provide some hints to serialization engine which
kind is preferred for given format?
E.g. @Serializer(king=SerializationKind.Binary)

With best regards,
Tagir Valeev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20190620/260b7ff2/attachment.html>

More information about the amber-spec-experts mailing list