java 构造json字符串,如何在Java中构造JSON数据

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"

}

]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值