Jackson - Serialize Map with Object as key to array

78 views Asked by At

I am migrating my Quarkus app from using Json-B to Jackson. Now I have difference with how Jackson and Json-B serialize Map where key is some Java Object.

Example of the transfer object:

public class Car {
  private Integer id;
  private String color;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}

My resource example:

@GET
@Path("/test")
public Map<Car, String> test() {
  Car car = new Car();
  car.setId(1);
  car.setColor("Red");
    
  Map<Car, String> map = new HashMap<>();
  map.put(car, "First");
  return map;
}

With Jackson result of serialization is (only use toString() for serializating Car object:

{
    "com.example.app.dto.Car@42773f1c": "First"
}

With Json-B result of serialization is:

[
    {
        "key": {
            "color": "Red",
            "id": 1
        },
        "value": "First"
    }
]

Is there any Jackson configuration that can achieve to have the same result with Jackson as Json-B provides, with maps having key as object? I can achieve it for this specific case with custom serializer, but I need a general solution.

1

There are 1 answers

1
Luca Basso Ricci On

Use a custom jackson serializer for your Car object and register it with a io.quarkus.jackson.ObjectMapperCustomizer.
You can find all information in official guide