JSON解析,用java语言举个例子
时间: 2024-05-09 14:21:58 浏览: 7
好的,首先需要导入相关的包,比如:
```java
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
```
然后可以使用 JSONObject 类和 JSONArray 类来解析 JSON 数据。比如,我们有以下 JSON 字符串:
```json
{
"name": "John",
"age": 30,
"city": "New York"
}
```
我们可以使用以下代码将其解析为 JSONObject 对象:
```java
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
try {
JSONObject jsonObj = new JSONObject(jsonString);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");
System.out.println(name + " " + age + " " + city);
} catch (JSONException e) {
e.printStackTrace();
}
```
输出结果:John 30 New York。
如果我们有以下 JSON 数组字符串:
```json
[{
"name": "John",
"age": 30,
"city": "New York"
}, {
"name": "Jane",
"age": 25,
"city": "Los Angeles"
}]
```
我们可以使用以下代码将其解析为 JSONArray 对象,并遍历其中的每个元素:
```java
String jsonArrayString = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"},{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonArrayString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");
System.out.println(name + " " + age + " " + city);
}
} catch (JSONException e) {
e.printStackTrace();
}
```
输出结果:
John 30 New York
Jane 25 Los Angeles
希望这个例子可以帮助你理解如何使用 Java 解析 JSON 数据。