Search code examples
javajsonserializationpojobuilder

How to create this JSONObject using java?


How do I create the following json using java classes and lombok's builder?

I used some json to pojo tool and created 2 classes: Entry.java and Testplan.java, added a method to convert String to json and managed to get a json object: {"suite_id":99,"name":"Some random name"}

I don't understand how to create one that would look like this:

{
  "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;
}

I convert String to json using this:

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

Here's how I started creating the object and got stuck:

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

To see what's happening I added this:

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

I expect to have have to combine these two classes and create a list of case_ids but can't wrap my head around it.


Solution

  • This worked:

    1. Created a new method of 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. and then used this method to convert pojo to json:
        protected <U> String toJson(U request) throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(request);
        }