在AjaxResult 里获取data字段并将其转换为指定类型的对象

This commit is contained in:
weiweiw 2024-09-23 10:34:25 +08:00
parent dc7a51eba6
commit 537cfe5c9b
2 changed files with 27 additions and 0 deletions

View File

@ -153,6 +153,11 @@
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>

View File

@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.Objects;
import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.utils.StringUtils;
import com.google.gson.Gson;
/**
* 操作消息提醒
@ -213,4 +214,25 @@ public class AjaxResult extends HashMap<String, Object>
super.put(key, value);
return this;
}
/**
* 获取data字段并将其转换为指定类型的对象
*
* @param clazz 目标类
* @param <T> 目标类型
* @return 转换后的对象或null如果data字段为空
*/
public <T> T getDataAs(Class<T> clazz) {
Object data = this.get(DATA_TAG); // 获取data字段
if (data == null) {
return null; // 如果data为空返回null
}
// 创建Gson实例
Gson gson = new Gson();
// 将data从LinkedHashMap转换为指定类型的对象
return gson.fromJson(gson.toJson(data), clazz);
}
}