Is there a way in Jackson to write HashMap in to a list of object and vice versa

I'd like to transform

 HashMap<String, Car> to JSON list of cars

when serializing and from

 List<Car> (JSON) to HashMap<String, Car> 

when deserializing.

I know I can write a custom serializer/deserializer but I was wondering if there was a easier/built in way in jackson to achieve this.

1 answer

  • answered 2018-01-12 14:27 Jonas

    Assuming that your HashMap's key is also in your value object (like a VIN for a car), so you can easily re-build the key later, then maybe the annotations @JsonGetter/@JsonSetter can help:

    Let's say you have something like a car rental station:

    import com.fasterxml.jackson.annotation.JsonGetter;
    import com.fasterxml.jackson.annotation.JsonSetter;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    public class CarRentalStation {
        private String location = "Atlanta";
        private Map<String, Car> cars = new HashMap<String, Car> (){{
            put("A123", new Car("A123", "BMW 120d"));
            put("B321", new Car("B321", "Volkswagen Golf 2.0 TDI"));
        public String getLocation() {
            return location;
        public List<Car> getCarsAsList() {
            return cars.values().stream().collect(Collectors.<Car>toList());
        public void setCarsAsList(List<Car> cars) {
            Map<String, Car> deserializedCars =, car -> car));
   = deserializedCars;
        //toString ...    

    The car looks like that:

    public class Car {
        private String vin;
        private String model;
        Car() {
        public Car(String vin, String model) {
   = vin;
            this.model = model;
        public String getVin() {
            return vin;
        public String getModel() {
            return model;
        // toString ... 

    You can easily serialize/ deserialize it:

    ObjectMapper om = new ObjectMapper();
    String json = om.writeValueAsString(new CarRentalStation());
    // prints: {"location":"Atlanta","cars":[{"vin":"B321","model":"Volkswagen Golf 2.0 TDI"},{"vin":"A123","model":"BMW 120d"}]}
    CarRentalStation deserializedCarRentalStation =  om.readValue(json, CarRentalStation.class);
    // prints: CarRentalStation{location='Atlanta', cars={B321=Car{vin='B321', model='Volkswagen Golf 2.0 TDI'}, A123=Car{vin='A123', model='BMW 120d'}}}