【问题标题】:Spring Boot Modify Default JSON responseSpring Boot 修改默认 JSON 响应
【发布时间】:2017-08-08 03:14:10
【问题描述】:

我有一个 REST 控制器,它返回如下产品列表:

电流输出

[  
   {  
      "id":1,
      "name":"Money market"
   },
   {  
      "id":2,
      "name":"Certificate of Deposit"
   },
   {  
      "id":3,
      "name":"Personal Savings"
   }
]

为了让我们的 JS 网格库正常工作,我需要将响应修改为如下所示:

期望的输出

{ "data" :
   [  
       {  
          "id":1,
          "name":"Money market"
       },
       {  
          "id":2,
          "name":"Certificate of Deposit"
       },
       {  
          "id":3,
          "name":"Personal Savings"
       }
    ]
}

控制器

@RequestMapping(value = "/api/products", method = RequestMethod.GET)
public ResponseEntity<?> getAllProducts() {

  List<Product> result = productService.findAll();
  return ResponseEntity.ok(result);
}

有没有使用原生 Spring 库修改 JSON 响应的简单方法?

【问题讨论】:

    标签: java json spring spring-boot


    【解决方案1】:

    使用org.json 库:

    JSONObject json = new JSONObject();
    json.put("data", result);
    

    put 方法添加或替换对象中的值。

    【讨论】:

      【解决方案2】:

      您可以将结果对象放入带有键“数据”和值作为结果的 Map。

      map.put("data", result);

      然后从 rest 方法中返回地图对象。

      return ResponseEntity.ok(map);

      【讨论】:

        猜你喜欢
        • 2015-05-20
        • 2015-08-30
        • 2017-03-08
        • 2015-06-06
        • 2017-04-23
        • 2019-01-13
        • 2020-02-19
        • 1970-01-01
        相关资源
        最近更新 更多