繁体   English   中英

用Java解码JSON格式

[英]Decoding JSON format in Java

我得到了一个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()

有json-lib可以解析JSON字符串。 请参阅O'Reilly上的这篇文章 它还显示了一个基于Maven的示例,因此是Ctrl-C / Ctrl-V(如果愿意,也可以使用Cmd)的一个很好的来源。

如果您只需要解析JSON数组,则可能有点过大,但是如果您使用Java 6,则可以在Java中使用JavaScript。然后,您可以将JavaScript数组转换为ArrayList或要在Java上使用的任何对象。 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数组,那么这可能会很有用。 您可以在《 Java平台的 脚本编制》和《 Java脚本编制程序员指南》下找到更多信息。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM