如何在Java中构造JSON数据 [英] How to construct JSON data in Java
本文介绍了如何在Java中构造JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Apache HttpClient来发布JSON请求.但是,我想将Json数据发送到目标系统的过程并不复杂.以下是我要发送的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"
}
}
}
在Java中,对json数据进行收缩的最佳和最简便的方法是什么?
What is the best and easiest way to contract above json data in Java?
推荐答案
使用POJO和和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;
}
}
您可以使用以下方法创建JSON:
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));
输出:
{
"name": "xyz",
"id": "428",
"mailId": [
"mailme@mail.com"
],
"bundle1": [
{
"number": "132344345",
"title": "title"
}
]
}
这篇关于如何在Java中构造JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文