java - 如何使用 JsonObject 在 Java 中创建正确的 Json

标签 java json

如何在 Java 中使用 JSONObject 创建如下所示的 JSON 对象?

{
    "fields": {
     "issuetype":{"id": "10004"},
     "project":{"key": "TES"},
     "reporter":{"name":"TestUser"},
     "summary":"Screen not responding",
     "description":"New Bug in UI. Screen not responding",
     "assignee":{"name":"Test"}

     }
}

到目前为止我已经尝试过

JsonObject issuetype = new JsonObject();
        issuetype.addProperty("id", "10004");
        JsonObject project = new JsonObject();
        project.addProperty("key", "TES");
        JsonObject reporter = new JsonObject();
        reporter.addProperty("name", "TestUser");
        JsonObject summary = new JsonObject();
        summary.addProperty("summary", "Screen not responding");
        JsonObject description = new JsonObject();
        description.addProperty("description", "New Bug in UI. Screen not responding");
        JsonObject assignee = new JsonObject();
        assignee.add("name", "Test");

有人可以帮我解决这个问题吗?

谢谢

最佳答案

您应该使用Json创建对象的工厂类builders :

JsonObject issuetype = Json.createObjectBuilder()
    .add("fields", Json.createObjectBuilder()
        .add("issuetype", Json.createObjectBuilder().add("id", "10004"))
        .add("project", Json.createObjectBuilder().add("key", "TES"))
        .add("reporter", Json.createObjectBuilder().add("name", "TestUser"))
        .add("summary", "Screen not responding")
        .add("description", "New Bug in UI. Screen not responding")
        .add("assignee", Json.createObjectBuilder().add("name", "Test"))
    )
    .build();

关于java - 如何使用 JsonObject 在 Java 中创建正确的 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052043/

相关文章:

json - 在 UIPickerView 上选择一行时如何用信息填充第二个 View Controller

android - 如何在android中将整数保存到sql数据库?

java - 使用 twilio 沙箱在 whatsapp 上发送多条媒体消息

java - 如何为 Java 创建 Kotlin 静态变量和函数?

java - XStream 不会调用 readObject()

c++ - 如何从 Qt 中的 JSON 数据中检索整数值

javascript - 使用保留字作为属性名,重温

java - hibernate 5 : generator class ="sequence" not working

java - 我可以从同一个 jar 文件执行两个不同的类吗?

json - 使用Dart将输入表单中的数据存储到JSON中