I would want to POST JSON request using Apache HttpClient. But the Json data is little complex that I would want to send to target system. Below is the json that I would send
{
"name":"xyz",
"id":"428",
"mailId":
[
"mailme@mail.com"
],
"bundle1":
{
"opwarden":
{
"number":"132344345",
"title":"title"
}
}
}
What is the best and easiest way to contract above json data in Java?
解决方案
With POJOs and ObjectMapper for Jackson:
public class Data {
private final String name;
private final String id;
private final List mailId;
private final List bundle1;
public Data(final String name, final String id, final List mailId, final List bundle1) {
this.name = name;
this.id = id;
this.mailId = mailId;
this.bundle1 = bundle1;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public List getMailId() {
return mailId;
}
public List getBundle1() {
return bundle1;
}
}
and Opwarden:
public class Opwarden {
private final String number;
private final String title;
public Opwarden(final String number, final String title) {
this.number = number;
this.title = title;
}
public String getNumber() {
return number;
}
public String getTitle() {
return title;
}
}
You can create a JSON with:
ObjectMapper objectMapper = new ObjectMapper();
Data data = new Data("xyz", "428", List.of("mailme@mail.com"), List.of(new Opwarden("132344345", "title")));
System.out.println(objectMapper.writeValueAsString(data));
The output:
{
"name": "xyz",
"id": "428",
"mailId": [
"mailme@mail.com"
],
"bundle1": [
{
"number": "132344345",
"title": "title"
}
]
}