JSON对象的JSON数组返回null

时间:2018-03-09 13:27:14

标签: java arrays json

我想阅读JSON数组

"connectTo":[   
    {
        "url": "wss://localhost/opt/siml"
    }   
],

来自JSON字符串:

{

"cluster":{
    "enabled":"true",
    "clusterName":"cluster0",
    "simlURL":"wss://localhost:5443/opt/siml"
},

"simlFieldWatchUrl":"fieldwatchholder.jsp",

"persistFolder":"clusterconfig/concentratorBPersist",

"sslCrtFile":"clusterconfig/certDirB/siml.crt",
"sslKeyFile":"clusterconfig/certDirB/siml.key",

"SIMLID":"TestServerB",

"localWebProxyServer":"localhost",
"localWebProxyPort":8080,
"SIMLProxyPort":8400,
"SIMLWebPort":8300,

"turnOnExtraSIMLWebSocket":"false",

"autoPromoteNewConnectionsFromPurgatory":true,

"connectTo":[   
    {
        "url": "wss://localhost/opt/siml"
    }   
],

"tempLogins":[
    {
        "username":"root",
        "password":"root"
    }
]

}

我读取网址的代码是:

JSONArray connectTo = (JSONArray) config.get("connectTo");
                System.out.println("Connect to : " + connectTo);
                for (Object o : connectTo) {
                    JSONObject connect = (JSONObject) o;
                    String url = (String) connect.get("url");
                    System.out.println(url);
                }

System.out.println(“连接到:”+ connectTo); 这是返回 连接到:[]

我读了一些旧问题,但没有得到满意的答复。请帮忙。并提前谢谢你:)

3 个答案:

答案 0 :(得分:3)

我只是假设config是一个JSONObject。

JSONArray connectTo = config.getJSONArray("connectTo");

config.get()返回一个对象,config.getJSONArray()返回JSONArray

答案 1 :(得分:1)

试试这个:

JSONArray connectTo =config.getJSONArray("connectTo");

                    System.out.println("Connect to : " + connectTo);
                    for (int i=0;i<connectTo.length();i++) 
    {
                        JSONObject connect = connectTo.getJSONObject(i);
                        String url = connect.get("url");
                        System.out.println(url);
                    }

答案 2 :(得分:0)

我让它像这样工作,不确定这是否有帮助:

var json = {
  "connectTo": [{
    "url": "wss://localhost/opt/siml"
  }]
};

for (var o = 0; o < json.connectTo.length; o++) {
  console.log(json.connectTo[o].url);
}