jsonobject如何通过key获取value中的集合
时间: 2024-05-07 19:15:30 浏览: 76
假设有以下json字符串:
```
{
"name": "John",
"age": 30,
"hobbies": ["reading", "running", "swimming"]
}
```
可以使用以下代码通过key获取value中的集合:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\",\"age\":30,\"hobbies\":[\"reading\",\"running\",\"swimming\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray hobbiesArray = jsonObject.getJSONArray("hobbies");
for (int i = 0; i < hobbiesArray.length(); i++) {
String hobby = hobbiesArray.getString(i);
System.out.println(hobby);
}
}
}
```
输出结果:
```
reading
running
swimming
```
可以看到,首先将json字符串转换为JSONObject对象,然后使用getJSONArray方法获取到对应key的JSONArray对象,最后遍历JSONArray对象获取每个元素的值。
阅读全文