You need to enable JavaScript to run this app. Java Spring Web服务如何根据请求参数动态设置JSON输出属性名
优惠活动
大模型
产品
解决方案
定价
更多

Java Spring Web服务如何根据请求参数动态设置JSON输出属性名

实现方案

由于Spring MVC默认通过Jackson序列化返回对象时,Java实体类的JSON属性名是编译期固定绑定的,无法动态替换为请求传入的路径参数,因此不需要引入自定义序列化器,直接用Map结构组织返回值即可实现需求——Jackson序列化Map时会完全按照Map的键值对生成对应JSON结构,不存在静态字段绑定的限制。

具体改造步骤

  • 调整Controller方法的返回类型,不再绑定固定的BatchPollingResponse作为返回泛型,改为ResponseEntity<Map<String, Object>>,适配动态结构的序列化要求
  • 保留原有路径参数的获取逻辑,已经通过@PathVariable拿到的waybill变量(即路径中Z2074350这类编码值),就是动态JSON属性名的直接来源
  • 按照目标JSON结构逐层组装嵌套Map:
    1. 先建一个内层Map,把waybill参数值作为Map的键,对应的值为原逻辑从restTemplate查询到的BatchPollingResponse业务对象
    2. 再建一个外层Map,把固定字符串result作为Map的键,对应的值为上一步组装好的内层Map
    3. 把外层Map作为ResponseEntity的返回体,交由Jackson完成自动序列化

改造后的参考代码

@GetMapping(value = "/batchpolling/{waybill}/{cp_id}", headers="Accept=application/json", produces="application/json")
public ResponseEntity<Map<String, Object>> getBatchPollingResponse(@PathVariable("waybill") String waybill) throws JsonProcessingException {
    Map<String, Object> finalResult = new HashMap<>();
    try {
        // 保留原有业务逻辑:通过restTemplate拉取对应运单的轮询结果
        BatchPollingResponse batchPollResponse = restTemplate.getForObject(url, BatchPollingResponse.class);
        
        // 组装带动态键的内层结构
        Map<String, Object> waybillEntry = new HashMap<>();
        waybillEntry.put(waybill, batchPollResponse);
        
        // 组装外层result结构
        finalResult.put("result", waybillEntry);
    } catch (Exception e) {
        LOGGER.error("Error processing OrderCreationMPS - getBatchPollingResponse", e);
        // 异常场景保持返回结构一致,避免前端解析异常
        Map<String, Object> errorEntry = new HashMap<>();
        errorEntry.put(waybill, "查询异常");
        finalResult.put("result", errorEntry);
    }
    return new ResponseEntity<>(finalResult, HttpStatus.OK);
}

实际输出效果

当请求路径中waybill参数值为Z2074350时,Jackson序列化生成的JSON将完全匹配预期结构:

{
  "result": {
    "Z2074350": {
      "latest_status": {
        "status": "delivered"
      }
    }
  }
}

后续请求传入其他waybill参数值时,JSON中对应的动态键会自动替换为实际的路径参数值,不需要修改任何业务逻辑代码。


内容的提问来源于stack exchange,提问作者Charan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.21 07:36:04