GSON 遍历json字符串
时间: 2023-10-18 12:27:54 浏览: 248
要遍历 JSON 字符串,你可以使用 GSON 库。下面是一个示例代码,展示了如何使用 GSON 解析和遍历 JSON 字符串:
```java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonTraversalExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 创建一个 Gson 对象
Gson gson = new Gson();
// 使用 JsonParser 解析 JSON 字符串为 JsonObject
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
// 遍历 JsonObject 的键值对
for (String key : jsonObject.keySet()) {
System.out.println("Key: " + key);
System.out.println("Value: " + jsonObject.get(key));
}
// 使用 Gson 将 JSON 字符串解析为指定类型的对象
Person person = gson.fromJson(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
}
// 定义一个 Person 类,用于存储解析后的 JSON 数据
private static class Person {
private String name;
private int age;
private String city;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCity() {
return city;
}
}
}
```
在这个示例中,我们使用 `JsonParser` 类将 JSON 字符串解析为 `JsonObject`,然后遍历 `JsonObject` 的键值对。同时,我们还使用了 `Gson` 对象将 JSON 字符串解析为 `Person` 对象,并获取对象的属性值。
记得在使用代码之前,先添加 GSON 库的依赖。希望这个示例能对你有所帮助!
阅读全文
相关推荐

















