使用 JSONObject 在 Java 中为以下结构创建嵌套的 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22042638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:14:03  来源:igfitidea点击:

Creating nested JSON object for the following structure in Java using JSONObject?

javajsonarraysjsonobject

提问by user3131769

I want to build a JSON Object similar to following the structure in java using JSONObject and JSONArray.

我想使用 JSONObject 和 JSONArray 构建一个类似于 Java 中的结构的 JSON 对象。

I have gone through various posts in stack overflow, which suggests using methods like push, put etc which I am unable to identify for JSONArray. Please help.

我已经浏览了堆栈溢出中的各种帖子,这建议使用我无法识别 JSONArray 的 push、put 等方法。请帮忙。

{
    "name": "sample",
    "def": [
        {
            "setId": 1,
            "setDef": [
                {
                    "name": "ABC",
                    "type": "STRING"
                },
                {
                    "name": "XYZ",
                    "type": "STRING"
                }
            ]
        },
        {
            "setId": 2,
            "setDef": [
                {
                    "name": "abc",
                    "type": "STRING"
                },
                {
                    "name": "xyz",
                    "type": "STRING"
                }
            ]
        }
    ]
}

采纳答案by goten

With the imports org.json.JSONArrayand org.json.JSONObject

随着进口org.json.JSONArrayorg.json.JSONObject

JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");

arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);

arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);

I did not include first array's second element for clarity. Hope you got the point though.

为清楚起见,我没有包含第一个数组的第二个元素。希望你明白这一点。

EDIT:

编辑:

The previous answer was assuming you were using org.json.JSONObjectand org.json.JSONArray.

上一个答案是假设您正在使用org.json.JSONObjectand org.json.JSONArray

For net.sf.json.JSONObjectand net.sf.json.JSONArray:

对于net.sf.json.JSONObjectnet.sf.json.JSONArray

JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");

arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);

arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);

Basically it's the same, replacing the method 'put' for 'element' in JSONObject, and 'put' for 'add' in JSONArray.

基本上是一样的,在 JSONObject 中为 'element' 替换了方法 'put',在 JSONArray 中为 'add' 替换了 'put'。

回答by ErstwhileIII

Here is one crude example. You should be able to refine. (You may be interested in this Java "tutorial" http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

这是一个粗略的例子。你应该可以细化。(您可能对这个 Java“教程”感兴趣http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

(This example uses the JSON reference implementation included in Java EE (and available here: https://java.net/projects/jsonp/downloads/directory/ri)

(此示例使用 Java EE 中包含的 JSON 参考实现(可在此处获得:https: //java.net/projects/jsonp/downloads/directory/ri

package com.demo;
import java.io.FileWriter;
import java.io.IOException;
import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class JSONExample {
public static void main(String[] args) {
    FileWriter writer = null;
    try {
        writer = new FileWriter("C:\Users\Joseph White\Downloads\jsontext.txt");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JsonGenerator gen = Json.createGenerator(writer);

    gen.writeStartObject().write("name", "sample")
        .writeStartArray("def")
          .writeStartObject().write("setId", 1)
             .writeStartArray("setDef")
                .writeStartObject().write("name", "ABC").write("type", "STRING")
                .writeEnd()
                .writeStartObject().write("name", "XYZ").write("type", "STRING")
                .writeEnd()
            .writeEnd()
          .writeEnd()
            .writeStartObject().write("setId", 2)
              .writeStartArray("setDef")
                .writeStartObject().write("name", "abc").write("type", "STRING")
                .writeEnd()
                .writeStartObject().write("name", "xyz").write("type", "STRING")
                .writeEnd()
              .writeEnd()
            .writeEnd()
          .writeEnd()
        .writeEnd();

    gen.close();

}

 }