Spring – Java将HashMap映射到多层Pojo

我有一个哈希映射Map< String,String>如果有以下值,请注意点表示层次结构:

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

我有pojo课程:

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**
}

有什么办法可以根据层次结构将HashMap映射到POJO类吗?我尝试使用jackson ObjectMapper mapper = new ObjectMapper();但它似乎能够映射1级对象.

解决方法:

您可以在Vehicle类的构造函数上使用@JsonCreator annotation

@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;
}

用法:

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);
上一篇:如何使用Jersey将POJO序列化为查询参数


下一篇:网站前台的三级联动数据封装