【问题标题】:How to create this JSONObject using java?如何使用 java 创建这个 JSONObject?
【发布时间】:2019-04-23 19:12:56
【问题描述】:

如何使用 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
      ]
    }
  ]
}

Testplan.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;
}

我使用以下方法将字符串转换为 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】:

    这行得通:

    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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-13
      • 2013-09-29
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      相关资源
      最近更新 更多