gpt4 book ai didi

java - 如何用Java构造JSON数据

转载 作者:行者123 更新时间:2023-12-02 01:26:37 24 4
gpt4 key购买 nike

我想使用 Apache HttpClient 发布 JSON 请求。但我想发送到目标系统的 Json 数据并不复杂。下面是我要发送的 json

{
"name":"xyz",
"id":"428",
"mailId":
[
"mailme@mail.com"
],
"bundle1":
{
"opwarden":
{
"number":"132344345",
"title":"title"
}
}
}

在 Java 中收缩上述 json 数据的最佳和最简单的方法是什么?

最佳答案

使用 POJO 和 ObjectMapper jackson :

public class Data {

private final String name;
private final String id;
private final List<String> mailId;
private final List<Opwarden> bundle1;

public Data(final String name, final String id, final List<String> mailId, final List<Opwarden> 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<String> getMailId() {
return mailId;
}

public List<Opwarden> getBundle1() {
return bundle1;
}
}

和奥普沃登:

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:

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 - 如何用Java构造JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56805274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com