Java - 从多个多维数组创建 JSON 对象

标签 java multidimensional-array

我正在尝试将一个非常复杂的数组结构转换为 JSON 对象,但我不确定如何进行转换。结构如下:

String[] foo = new String[10];
String[][] bar = new String[10][8];
String[][] blargh = new String[8][2];
// Populate foo
foo[0] = "foo1";
// ... and so on
bar[0][0] = "bar1";
// ... and so on
blargh[0][0] = "blargh1;"
// ... and so on

然后:

public JSONObject createJSONObject() {
/* Now, I would like to create an object with the structue:
   [{
    foo[0] : {
        bar[0][0] : {
            // more key-pair values, including blargh[0][0] and blargh[0][1]
        },
        bar[0][1] : {
            // values of blargh[1][0] and blargh[1][1]
        },
        // etc...
    },
    foo[1] : {
        bar[1][0] : {
            /* primary index of bar will always match index of foo, as will the primary index of blargh */
        },
        // etc..
    },
    // etc..
    }]
    // return the JSON encoded object
}

这对我来说似乎相当复杂,所以如果我的问题/代码/结构令人困惑或不清楚,请告诉我。

最佳答案

将其分解为可管理的 block 。创建了解如何单独构造每个嵌套对象的方法,然后在适当的时候调用它们。例如,像这样的东西:

public JSONObject createJSONObject() {
    JSONObject result = new JSONObject();
    for (int fooIndex = 0; fooIndex < foo.length; fooIndex++) {
        result.put(foo[fooIndex], createBarJsonObject(fooIndex));
    }

    return result;
}

private JSONObject createBarJsonObject(int index) {
    JSONObject result = new JSONObject();
    String[] keys = bar[index];
    for (int barIndex = 0; barIndex < keys.length; barIndex++) {
        result.put(keys[barIndex], createBlarghJsonObject(fooIndex));
    }

    return result;
}

private JSONObject createBlarghJsonObject(int index) {
    JSONObject result = new JSONObject();
    String[] keyValue = blargh[index];
    result.put(keyValue[0], keyValue[1]);

    return result;
}

关于Java - 从多个多维数组创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7382351/

相关文章:

java - <key, value> 对的线程安全容器

java - 读取文本文件并创建一个二维数组

C++:生成未知深度的多维 vector

c - 遍历二维数组的二维子数组的最佳方法是什么?

C++多维数组初始化

java - 当数组位于数组列表中时如何访问数组?

java - 尝试从数据库中检索值时出现 SQLite 数据库错误

javascript - 如何删除二维数组中具有空值Javascript的索引自定义元素

php - 从嵌套数组中提取数据

java - 解析文件的单元测试,如何从应用程序内部加载文件?