【问题标题】:JSON by Jackson: hide field name but keep the valueJackson的JSON:隐藏字段名称但保留值
【发布时间】:2022-01-25 11:52:44
【问题描述】:

我正在使用 Jackson 库创建 JSON。

例如,我有一个员工,其中包含以下字段:姓名、姓氏和一对信息列表,如下所示

    @Data
        @NoArgsConstructors
        public class EmployeeJSON {
        
        private String name;
        private String surname;
        private List<CoupleInfo> addresses = new ArrayList<>();
// this class continue with regular implementation to fill the fields and creating an object for CoupleInfo

为 CoupleInfo 实现了一个类:

@Data
@NoArgsConstructors
public class CoupleInfo {
private List<String> list = new ArrayList<>();

public CoupleInfo(String place, String address){
list.add(place);
list.add(address);
      }
}

我想进入 JSON,当然包含字段名称和姓氏,字段地址填充为一对值的列表(作为 JSON 中的数组),但在数组内部没有字段列表.

怎么做?

我尝试使用@JsonIgnore,但所有字段和值都消失了。

最后得到这个:

{"name":"giulio", "surname":"marri", "addresses":[["roma","piazza liberta'"],["torino","via torre"]]}

改为:

 {"name":"giulio", "surname":"marri", "addresses":[{"list":["roma","piazza liberta'"]},{"list":["torino","via torre"]}}

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    您可以使用@JsonValue 将地址作为没有字段名称的列表列表:

    @Data
    @NoArgsConstructor
    public class CoupleInfo {
    
        public List<String> list = new ArrayList<>();
    
        public CoupleInfo(String place, String address){
            list.add(place);
            list.add(address);
        }
    
        @JsonValue
        public List<String> getList() {
            return list;
        }
    }
    

    结果将是:

    {"name":"giulio","surname":"marri","addresses":[["roma","piazza liberta"],["torino","via torre"]]}
    

    【讨论】:

    • 非常感谢,它工作正常
    猜你喜欢
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多