java - 如何用Java构造JSON数据

标签 java json http apache-httpclient-4.x

我想使用 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/

相关文章:

json - ConvertFrom-Json最大长度

sql - 无法从 Postgres 中的 JSON 列中提取数据

c# - HttpContext.Cache 属性存储?

Java 8 流,为什么要编译第 2 部分……或者什么是方法引用,真的吗?

java - 为什么我的 key 标识符不匹配?

mysql - 从多个文件输入读取 JSON 数据

qt - QNetworkAccessManager:从串行 QIODevice 发布 http multipart

java - 每月总计金额的 SQL 数据透视表

Java 用 "broken vertical bar"分割 ISO-8859-1 字符串

http - 在线 HTTP 客户端