使用 Lombok 注释生成 json 请求正文

Generate json request body using Lombok annotation

我尝试了多种模式,但仍然没有成功我如何创建 JSON 具有嵌套 JSON 对象的数组对象,如下所示

{
  "deduction": [
    {
      "id": "50258779",
      "amount": {
        "value": 13.24,
        "currency": "INR"
      },
      "transfer": "DEPOSIT",
      "fund": "RL",
      "description": "TD description",
      "code": "codeNumber"
    },
    {
      "id": "50258779",
      "amount": {
        "value": 13.24,
        "currency": "INR"
      },
      "transfer": "DEPOSIT",
      "fund": "RL",
      "description": "TD description",
      "code": "codeNumber"
    }
  ]
}

我已生成 Class 来构建此请求架构:

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.util.List;


@Builder
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Transf{

    private List<Deduction> deduction;

    @Builder
    @Getter
    @Setter
    public class Deduction {

        private Amount amount;
        private String transfer;
        private String code;
        private String fund;
        private String description;
        private Integer id;

    }

    @Builder
    @Getter
    @Setter
    public class Amount {

        private String currency;
        private Double value;

    }
}

正在尝试创建 json 请求正文以放心发送

public Transf trans()
    {
        return Transf.builder()
            .deduction(Transf.Deduction.builder().transfer("")).build();
    }

但是遇到语法错误,需要知道我怎样才能让它工作

而不是

Transf.Deduction.builder().transfer("")

你需要

Transf.Deduction.builder().transfer("").build()

首先,您定义 private List<Deduction> deduction; --> 您将提供 List

其次,要使生成器工作,您必须调用 .build()

public Transf trans() {
    return Transf.builder()
            .deduction(Arrays.asList(Transf.Deduction.builder().transfer("").build()))
            .build();
}