如何使用java创建此JSONObject?

问题描述 投票:0回答:1

如何使用java类和lombok的构建器创建以下json?

我使用了一些json to pojo工具并创建了2个类:Entry.javaTestplan.java,添加了一个方法将String转换为json并设法获得一个json对象:{"suite_id":99,"name":"Some random name"}

我不明白如何创建一个看起来像这样的:

{
  "name": "System test",
  "entries": [
    {
      "suite_id": 1,
      "name": "Custom run name"
    },
    {
      "suite_id": 1,
      "include_all": false,
      "case_ids": [
        1,
        2,
        3,
        5
      ]
    }
  ]
}

test plan.Java


@Data
@Builder
public class Testplan {

    @JsonProperty("name")
    public String name;
    @JsonProperty("entries")
    public List<Entry> entries = null;
}

entry.Java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Entry {

    @JsonProperty("suite_id")
    public Integer suiteId;
    @JsonProperty("name")
    public String name;
    @JsonProperty("include_all")
    public Boolean includeAll;
    @JsonProperty("case_ids")
    public List<Integer> caseIds = null;
}

我使用这个将String转换为json:

    public <U> String toJson(U request) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper()
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper.writeValueAsString(request);
    }

这是我开始创建对象并陷入困境的方式:

    public static Entry getRequestTemplate() {
        Entry entry = new Entry();
        entry.setName("Here's some name");
        entry.setSuiteId(16);
        return entry;
    }

为了看看发生了什么,我添加了这个:

    @Test
    public void showJson() throws JsonProcessingException {
        String json = toJson(getRequestTemplate());
        System.out.println(json);
    }

我希望必须结合这两个类并创建一个case_ids列表,但不能包围我的头。

java json serialization pojo builder
1个回答
0
投票

这有效:

  1. 创建了Testplan的新方法:
    public Testplan kek2() {
        Testplan testplan = Testplan.builder()
                .name("System test")
                .entries(Lists.newArrayList(Entry.builder()
                        .name("Custom run name")
                        .suiteId(1)
                        .includeAll(false)
                        .caseIds(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)))
                        .build()))
                .build();
        System.out.println(testplan);
        return testplan;
    }
  1. 然后使用此方法将pojo转换为json:
    protected <U> String toJson(U request) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(request);
    }
© www.soinside.com 2019 - 2024. All rights reserved.