Jackson to deserialize wrapper class with array of primitive types

Viewed 1208

I have a class as follows, wrapping array of bytes:

public final class Plan {
  private byte[] bytes;
  private int peekIdx;

  public Plan(byte[] bytes, int peekIdx) {
      this.bytes = bytes;
      this.peekIdx = peekIdx;
  }

  public Plan(byte[] bytes) {
      this(bytes, 0);
  }

  //bunch more methods
}

This is contained in other objects as

public final class Agent {
     private Plan plan;
     //bunch more properties...
}

Now I want to deserialize a JSON like

{"plan": [0, 1, 2]}

as an Agent. However I can't figure out how to annotate Plan to achieve this. If it was just byte[] there wouldn't be an issue as this would correspond directly to a named property in Agent that can be put as @JsonProperty("plan"), but I somehow need to tell Jackson how to wrap the array in a Plan object. How to achieve this? Does it really require a custom serializer?

2 Answers

Try putting @JsonValue on the bytes-getter in the Plan class. It will tell Jackson that the class should be serialized using only that value. Also, a creator needs to be specified as below.

Like this:

class Plan {


  // ...

  @JsonCreator
  public Plan(byte[] bytes) {
    this(bytes, 0);
  }

  @JsonValue
  public byte[] getBytes() {
      return bytes;
  }

  // ...

}

You can annotate your second constructor with @JsonCreator, specifying the name of the JSON field to be sent as the byte array parameter:

@JsonCreator
public Plan(@JsonProperty("plan") byte[] bytes) {
    this(bytes, 0);
}

This tells Jackson to use this constructor, sending to it the value of the plan field of the JSON object.

Related