如何将所有@PostMapping参数添加到Map?

时间:2017-09-13 12:58:43

标签: java spring web-services spring-web

我想提供一个POST servlet,它接受以下JSON内容:

{
  "name": John
  "age": 25,
  "some": "more",
  "params: "should",
  "get": "mapped"
}

其中两个属性应显式映射到已定义的参数。所有其他参数都应该放在Map<String, String>

问题:如何让Spring将它们直接映射到bean的地图中?

@RestController
public void MyServlet {
   @PostMapping
   public void post(@RequestBody PostBean bean) {

   }
}

public class PostBean {
   private String name;
   private String age;

   //all other json properties should go here
   private Map<String, String> map;
}

1 个答案:

答案 0 :(得分:0)

public class PostBean {
    private Map<String, String> map;

    @JsonAnyGetter
    public Map<String, String> getMap() {
        return map;
    }

    @JsonAnySetter
    public void setMap(String name, String value) {
        if (this.map == null) map = new HashMap<>();
        this.map.put(name, value);
    }
}