【问题标题】:Changing the JSON output property dynamically in Java在 Java 中动态更改 JSON 输出属性
【发布时间】:2020-10-24 19:22:01
【问题描述】:

我想将输出 JSON 的属性设置为输入值,因此对于每个请求,属性名称都会发生变化。

这是我的网络服务的获取请求 URL: http://10.0.75.1:7001/polling/Z2074350/ -> Z2074350 是我需要创建 JSON 属性的值:

我如何做到这一点?

我的控制器如下所示:

@GetMapping(value = "/batchpolling/{waybill}/{cp_id}", headers="Accept=application/json", produces="application/json")
    
public ResponseEntity<BatchPollingResponse> getBatchPollingResponse( @PathVariable("waybill") String waybill) throws JsonProcessingException {
            
        BatchPollingResponse batchPollResponse = null;
        try {
            ----------------------
            batchPollResponse = restTemplate.getForObject(url, BatchPollingResponse.class);
            ----------------------
        }catch(Exception e) {
            LOGGER.error("Error processing OrderCreationMPS - getBatchPollingResponse");
            e.printStackTrace();
        }
            return new ResponseEntity<BatchPollingResponse>( batchPollResponse, HttpStatus.OK );
        
    }

我的 JSON 输出如下:

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

【问题讨论】:

    标签: java json rest


    【解决方案1】:

    如果您想要动态属性作为响应,只需尝试在 ResponseEntity 对象中传递 Map&lt;String, BatchPollingResponse&gt; 并将您的属性作为键。

    @GetMapping(value = "/batchpolling/{waybill}/{cp_id}", headers="Accept=application/json", produces="application/json")
    public ResponseEntity<Map<String, BatchPollingResponse>> getBatchPollingResponse( @PathVariable("waybill") String waybill) throws JsonProcessingException {
                
            BatchPollingResponse batchPollResponse = null;
            try {
                ----------------------
                batchPollResponse = restTemplate.getForObject(url, BatchPollingResponse.class);
                ----------------------
            }catch(Exception e) {
                LOGGER.error("Error processing OrderCreationMPS - getBatchPollingResponse");
                e.printStackTrace();
            }
                return ResponseEntity.ok(Map.of(waybill, batchPollResponse));
            
        }
    

    【讨论】:

    • 我在问题中添加了更多信息,请您再检查一次,让我知道实现所需的位置和需要进行哪些更改
    • @Charan 你能不能也显示一个BatchPoolingResponse 类?
    • 公共类 BatchPollingResponse { 私有元元;私有 BatchPollingResult 结果;公共元 getMeta() { 返回元; } public void setMeta(Meta meta) { this.meta = meta; } public BatchPollingResult getResult() { 返回结果; } public void setResult(BatchPollingResult 结果) { this.result = result; } }
    • 公共类 BatchPollingResult { 私有 WayBillResponse 运单; public WayBillResponse getWaybill() { 返回运单; } public void setWaybill(WayBillResponse waybill) { this.waybill = waybill; } }
    • @Charan 我想在wayBill refrence 里面有latestStatus 引用,它有status 属性,对吧?试试我更新的帖子解决方案,上面 ^
    猜你喜欢
    • 2019-08-11
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2017-07-28
    相关资源
    最近更新 更多