访问json数组的维度(Java)

时间:2017-12-02 20:54:31

标签: java json gson

我有这段代码:

String sURL = "https://example.com/json"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();

// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
String names = rootobj.get("names").getAsString(); 
System.out.println(names);

如何在倒数第二行访问数组的第二级? “名字”是第一个维度正常的维度 在PHP中,解决方案是

$var = json[...][...] //for accessing the second dimension.

这是如何在Java中完成的?像rootobj.get(“names / surname”)之类的东西不起作用。

2 个答案:

答案 0 :(得分:0)

根据您的代码,我假设您使用GSON进行JSON处理。如果您的JSON元素是一个数组,您可以使用get(index)访问其元素。草绘在这里:

//Not taking care of possible null values here
JsonObject rootobj = ...
JsonElement elem = rootobj.get("names");
if (elem.isJsonArray()) {
    JsonArray elemArray = elem.getAsJsonArray();

    JsonElement innerElem = elemArray.get(0);
    if (innerElem.isJsonArray()) {
        JsonArray innerArray = innerElem.getAsJsonArray();
        //Now you can access the elements using get(..)
        //E.g. innerArray.get(2);
    }
}

当然,阅读并不是那么好。您还可以查看JsonPath,它可以简化导航到JSON文档中的特定部分。

<强>更新: 在您提到的文档中,您想要提取哪个值?数组元素的id值(根据你的评论之一)?对于这里的this示例,可以这样做:

JsonElement root = jp.parse....
JsonArray rootArray = root.getAsJsonArray(); //Without check whether it is really an array
//By the following you would extract the id 6104546
//Access an other array position if you want the second etc. element
System.out.println(rootArray.get(0).getAsJsonObject().get("id")); 

否则请更详细地解释您想要什么(您发布的代码与您引用的json示例不匹配)。

答案 1 :(得分:0)

在您的Github链接中,您的根元素是一个数组,而不是一个对象。 (并且没有names属性)

所以你需要

root.getAsJsonArray();

然后,您将循环遍历此数组的长度,并使用get(i)来访问特定对象。

从该对象中,使用另一个get方法来访问它的一个属性