Search code examples
javaspringhashmappojo

Spring - Java Map HashMap to Multi-Layer Pojo


I have a hash map Map<String, String> that has following value, please note that the dot indicates the hierarchy:

+--------------------+-----------+
|    Key             |  Value    |
+--------------------+-----------+
| car.color          | blue      |
| car.engine.make    | mitsubishi|
| car.engine.power   | 120       |
+--------------------+-----------+

I have pojo classes:

public class Vehicle {

    private Car car;
   **Setters and Getters Below*  
}    

public class Car {
    private String color;

    private Engine engine;
    **Setters and Getters Below*      
}

public class Engine {
    private String make;

    private Integer power;
    **Setters and Getters Below**
}

Is there any way i can map the HashMap into the POJO class based on the hierarchy? I tried to use jackson ObjectMapper mapper = new ObjectMapper(); but it seems able to map 1 level of object.


Solution

  • You could use @JsonCreator annotation on your Vehicle class' constructor:

    @JsonCreator
    public Vehicle(Map<String, String> map) {
        String color = map.get("car.color");
        String make = map.get("car.engine.make");
        Integer power = Integer.valueOf(map.get("car.engine.power"));
        Engine engine = new Engine();
        engine.setMake(make);
        engine.setPower(power);
        Car car = new Car();
        car.setColor(color);
        car.setEngine(engine);
        this.car = car;
    }
    

    Usage:

    Map<String, String> map = new HashMap<>();
    map.put("car.color", "blue");
    map.put("car.engine.make", "mitsubishi");
    map.put("car.engine.power", "120");
    
    ObjectMapper mapper = new ObjectMapper();
    
    Vehicle vehicle = mapper.convertValue(map, Vehicle.class);