0

I want to create a request body to test an API. The request body is a complex JSON as below:

{
  "certificate_registry": {
    "images": [
      {
        "url": "https://path.jpg"
      }
    ],
    "truck": {
      "plate": "aaaa-1111",
      "truck_model_id": 1,
      "truck_type_id": 1
    }
  }
}

Please suggest me what is the best way to create new complex JSON in java?

I used the tool online but it creates many classes for only 1 request body. It's not easy to understand, maintain.

1 Answer 1

2

This is something you can do by marshalling POJO's to JSON. For example with a framework such as Jackson.

As described in this tutorial you can use a Jackson ObjectMapper:

import com.brunozambiazi.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Calendar;
import java.util.HashSet;

public class SerializationTest {

    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setId(1L);
        user.setName("User");
        user.setBirthDate(Calendar.getInstance());
        user.setEmails(new HashSet<String>());
        user.getEmails().add("[email protected]");
        user.getEmails().add("[email protected]");

        ObjectMapper mapper = new ObjectMapper();

        String json = mapper.writeValueAsString(user);
        System.out.println(json);
    }

}

That will result in:

{"id":1,"name":"User","birthDate":1439662844272,"emails":["[email protected]","[email protected]"]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.