【问题标题】:Spring/Jackson RequestParam with HashMap from Angular来自 Angular 的带有 HashMap 的 Spring/Jackson RequestParam
【发布时间】:2016-03-21 01:43:04
【问题描述】:

试图了解发送值的 Hashmap 有什么问题。

客户端(角度)

var params = {
    year: reportYear,
    reportAgg: {
        "interest": "Java",
        "domain": "JavaCodeGeeks.com"
    }
};

return $http.post('test/' + pathVariable1 + '/',
    $.param(params), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });

服务器端(Spring/Jackson)

@RequestMapping(value = RqMapping, method = RequestMethod.POST)
public ResponseEntity sendReports(
    final @PathVariable(value = "pathVariable1") String organizationId,
    final @RequestParam(value = "year", required = true) int requestedYear,
    final @RequestParam(value = "reportAgg", required = false) Map<String, String> reportAgg,
    final HttpServletRequest request) {

request.getParametersMap 中可以看到预期的reportAgg[interest]reportAgg[domain],但我仍然在映射中得到reportAgg 的空值。

【问题讨论】:

标签: java angularjs spring spring-mvc jackson


【解决方案1】:

可以使用 JackSon 的 ObjectMapper 转换成 HashMap

 @RequestMapping(value = RqMapping, method = RequestMethod.POST)
    public ResponseEntity sendReports(
        final @PathVariable(value = "pathVariable1") String organizationId,
        final @RequestParam(value = "year", required = true) int requestedYear,
        final @RequestParam(value = "reportAgg", required = false) String reportAgg,
        final HttpServletRequest request) {
                ObjectMapper mapper = new ObjectMapper();
                String json = reportAgg;

                Map<String, String> map = new HashMap<String, String>();

                // convert JSON string to Map
                map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});

                System.out.println(map ); // out put as HashMap<String, String>

}// end of sendReports()

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2013-10-25
    • 2015-01-14
    • 2017-02-08
    相关资源
    最近更新 更多