java用fastjson获取json中的value的值
时间: 2023-05-26 12:05:32 浏览: 66
使用 FastJson 读取 JSON 中 value 的值有多种方法,以下是几种常用的方法:
1. 使用 JavaBean 对象映射
定义一个 JavaBean 对象,属性名和 JSON 字段名一致,然后通过调用 FastJson 的 `JSONObject.parseObject()` 方法将 JSON 字符串转化为 JavaBean 对象。
示例代码:
```java
public class User {
private String name;
private int age;
// getter and setter methods
}
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Tom\",\"age\":20}";
User user = JSONObject.parseObject(jsonStr, User.class);
System.out.println(user.getName() + ", " + user.getAge());
}
```
输出结果:`Tom, 20`
2. 使用 JSONObject 对象获取
使用 FastJson 的 `JSONObject` 类来解析 JSON 字符串,并通过调用 `get*()` 方法获取值,其中 `*` 表示对应 JSON 字段名的首字母大写的属性名。
示例代码:
```java
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Tom\",\"age\":20}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
System.out.println(name + ", " + age);
}
```
输出结果:`Tom, 20`
3. 使用 JSONPath 表达式获取
JSONPath 是一种类似于 XPath 的语法,可以通过表达式获取 JSON 中的值。FastJson 提供了 `JSONPath` 类来支持这种方式。
示例代码:
```java
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Tom\",\"age\":20}";
String name = JSONPath.read(jsonStr, "$.name").toString();
int age = Integer.parseInt(JSONPath.read(jsonStr, "$.age").toString());
System.out.println(name + ", " + age);
}
```
输出结果:`Tom, 20`