获取Object JsonResult里面的数据
时间: 2024-03-01 12:54:01 浏览: 31
假设你有一个 `JsonResult` 对象,可以通过以下步骤获取它里面的数据:
1. 使用 `getAsJsonObject()` 方法将 `JsonResult` 对象转换为 `JsonObject` 对象。
```java
JsonResult result = ...;
JsonObject jsonObject = result.getAsJsonObject();
```
2. 使用 `get()` 方法获取指定 key 对应的 value,返回值为 `JsonElement` 类型,需要进行类型转换。
```java
JsonResult result = ...;
JsonObject jsonObject = result.getAsJsonObject();
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
```
3. 使用 `getAsJsonPrimitive()` 方法获取指定 key 对应的 value,返回值为 `JsonPrimitive` 类型,可以直接获取 value。
```java
JsonResult result = ...;
JsonObject jsonObject = result.getAsJsonObject();
String name = jsonObject.get("name").getAsJsonPrimitive().getAsString();
int age = jsonObject.get("age").getAsJsonPrimitive().getAsInt();
```
4. 使用 `has()` 方法判断指定 key 是否存在。
```java
JsonResult result = ...;
JsonObject jsonObject = result.getAsJsonObject();
boolean hasName = jsonObject.has("name");
boolean hasGender = jsonObject.has("gender");
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![dll](https://img-home.csdnimg.cn/images/20210720083646.png)