如何在 Java 中构造 JSON 数据 [英] How to construct JSON data in Java

查看:25
本文介绍了如何在 Java 中构造 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Apache HttpClient POST 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 和 ObjectMapper for Jackson:

With POJOs and ObjectMapper for 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;
    }
}

和 Opwarden:

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;
    }
}

您可以使用以下命令创建 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆