【问题标题】:Spring data util pair rename json nameSpring data util对重命名json名称
【发布时间】:2019-10-18 15:03:27
【问题描述】:

我在这里的第一篇文章。我正在研究一个 API,但我发现了一个我不知道如何解决的问题。 我正在尝试获取数据库中所有产品的剩余库存。我正在使用带有 Spring Data 依赖项的 Spring boot 和 MongoDB。 这是我的代码:

@GetMapping("/remaining-stock")
    public ResponseEntity<List<Pair<String, Integer>>> showAllStock() throws EmptyDepositException{
        List<Pair<String, Integer>> allStock;
        try {
            allStock = depServ.showAllStock();
        }catch(EmptyDepositException ex) {
            allStock = null;
        }
        return ResponseEntity.ok(allStock);
    }

当我执行 GET 请求时,这是我得到的 JSON:

[
    {
        "first": "Water",
        "second": 5
    },
    {
        "first": "Milk",
        "second": 40
    }
]

值没问题,但我想用更好的名称重命名变量名称,如下所示:

[
    {
        "Product name": "Water",
        "Remaining stock": 5
    },
    {
        "Product name": "Milk",
        "Remaining stock": 40
    }
]

有办法做到这一点吗?

对不起我的英语,我来自阿根廷,所以可能有些不清楚。我希望你能帮助我。 提前谢谢大家。

【问题讨论】:

  • 您应该使用 DTO 而不是 Pair,然后您可以随意命名属性

标签: java spring mongodb spring-boot spring-data-mongodb


【解决方案1】:

您可以使用@JsonProperty annotation,它表示field name 被用作属性名称而不做任何修改,但它可以指定为非空值以指定不同的名称。属性名是指外部使用的名称,如 JSON 对象中的field name

public class Product implements Serializable {

    @JsonProperty("Product name")
    private String first;

    @JsonProperty("Remaining stock")
    private long second;

    // implement methods for getters and setters
}

【讨论】:

    【解决方案2】:

    使用 Pair Class,您无法做到这一点。我建议您创建一个如下所示的 DTO 类:

    public class CustomPair {
        @JsonProperty("Product name")
        private String first;
        @JsonProperty("Remaining stock")
        private String second;
    
        // standard getters and setters
    }
    

    那么你的控制器会是这样的:

    @GetMapping("/remaining-stock")
        public ResponseEntity<List<CustomPair>> showAllStock() throws EmptyDepositException{
            List<CustomPair> allStock;
            try {
                allStock = depServ.showAllStock(); // depServ.showAllStock(); should return List<CustomPair>
            }catch(EmptyDepositException ex) {
                allStock = null;
            }
            return ResponseEntity.ok(allStock);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2020-08-24
      • 2014-03-03
      相关资源
      最近更新 更多