Java 解析 JSON 字符串:Gson 库使用指南
Java 中可以使用 Json 库来解析 Json 字符串,常用的 Json 库有 Gson 和 Jackson。
以下是使用 Gson 库解析 Json 字符串的示例:
- 导入 Gson 库
import com.google.gson.Gson;
- 创建 Gson 对象
Gson gson = new Gson();
- 使用 fromJson 方法将 Json 字符串转换为 Java 对象
String jsonStr = '{"name":"John", "age":30, "city":"New York"}';
Person person = gson.fromJson(jsonStr, Person.class);
其中,Person 是一个 Java 类,用于存储 Json 中的数据。示例中的 Person 类定义如下:
class Person {
private String name;
private int age;
private String city;
// getter 和 setter 方法省略
}
从 Json 字符串中解析出来的数据会存储在 Person 对象的属性中。
- 访问解析出来的数据
System.out.println(person.getName()); // 输出:John
System.out.println(person.getAge()); // 输出:30
System.out.println(person.getCity()); // 输出:New York
注意:在使用 Gson 库解析 Json 字符串时,要保证 Json 字符串的格式正确,否则会抛出 JsonSyntaxException 异常。
原文地址: https://www.cveoy.top/t/topic/mSXK 著作权归作者所有。请勿转载和采集!