Prefix field when serializing with Jackson

Viewed 327

I'd like to prefix a field with a string value whenever the object gets serialized. Is there a way to do this with Jackson? I'd like to prefix the class name to the id.

public class CarClass {
  public Long id;
  public String name;
  ......
}

And example class would be...

CarClass car1 = new CarClass (1,"First car");

And I want it to be searilized like so:

{ 
  "id": "carClass-1",
  "name": "First car"
}
1 Answers

try JsonGetter annotation:

public class CarClass {
  public Long id;
  public String name;
  
  @JsonGetter("id")
  public String getPrefixedId() {
    return "carClass-" + id;
  }
}

Jackson annotations

Related