4

我得到了一个 JSON(编码)格式的嵌套数组,看起来像这样;

[
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,3450]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,34534]]]

所以我有一个包含三个数组的大数组(有时可能是 2 个或三个以上的数组),这三个数组中的每一个都包含一些数组,在上面的例子中。

什么是反向过程(解码格式)?我的意思是,如果我想从这些数组中获取这些值怎么办。

我尝试了 org.json Java API,对吗:

JSON JSONArray list = new JSONArray();
list.get()
4

4 回答 4

2

有 json-lib 来解析 JSON 字符串。请参阅有关 O'Reilly 的这篇文章。它还显示了一个基于 maven 的示例,因此是 Ctrl-C/Ctrl-V(或 Cmd,如果您愿意)的良好来源。

于 2010-09-15T06:48:55.923 回答
2

如果您只需要解析 JSON 数组,这可能有点矫枉过正,但如果您使用 Java 6,则可以在 Java 中使用 JavaScript。然后您可以将 JavaScript 数组转换为 ArrayList 或任何您想在Java 方面,因为您可以访问嵌入的 JavaScript 函数中的 Java 类。

将 JavaScript 嵌入到 Java 中看起来类似于:

// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");

// evaluate JavaScript code
engine.eval("function someFunction(param) {...}");

// you can also use an external script
//engine.eval(new java.io.FileReader("/path/to/script.js"));

// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;

// invoke your global function
Object result = inv.invokeFunction("someFunction", param);

如果您想做的不仅仅是将 JSON 数组转换为 Java 数组,这可能会很有用。您可以在Scripting for the Java PlatformJava Scripting Programmer's Guide中找到更多信息。

于 2010-09-15T10:07:08.357 回答
2

json.org 上有一些免费的 JSON 解码和编码类:http: //www.json.org/java/index.html

于 2010-09-15T10:19:43.193 回答
1
    someArray[] array = [
    [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]],
    [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,3450]],
    [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,34534]]]


    JSONArray superMasterArray = new JSONArray(array);
    if(superMasterArray != null){
        for(int i = 0; i < superMasterArray.length(); i++ ){
        JSONArray masterArray = (JSONArray) superMasterArray.get(i);
            for(int j = 0; j< masterArray.length(); j++){
                 JSONArray innerArray = (JSONArray) masterArray.get(j);
                 innerArray.getint(0);// gives 1st element of the inner array that is 1234
                 innerArray.getint(1);// gives 245
                 innerArray.getint(2);// gives 10
// if you dont know how many element in the given array, then loop it with size of array 
                }
            }
    }
于 2010-09-15T09:41:24.137 回答