public
class
User
extends
BaseEntity
{
private
String
account
;
private
String
email
;
将对象装换为map方法如下:
* 将对象装换为map
* @param bean
* @return
public
static
<
T
>
Map
<
String
,
Object
>
beanToMap
(
T
bean
)
{
Map
<
String
,
Object
>
map
=
new
HashMap
(
)
;
if
(
bean
!=
null
)
{
BeanMap
beanMap
=
BeanMap
.
create
(
bean
)
;
for
(
Object
key
:
beanMap
.
keySet
(
)
)
{
map
.
put
(
key
+
""
,
beanMap
.
get
(
key
)
)
;
return
map
;
测试方法:
public static void main(String[] args) {
User user = new User();
user.setAccount("account");
user.setEmail("2@qq.com");
Map<String, Object> map = beanToMap(user);
System.out.println("map " + map);
System.out.println("user " + user);
输出结果:
map {account=account, email=2@qq.com}
user User(account=account, email=2@qq.com)
环境: springboot假设实体类User定义如下:User.class@Datapublic class User extends BaseEntity { private String account; private String email;}编写将对象装换为map方法如下: /** * 将对象装换为map * * @param bean * @return */ public static <T>
SpringBoot将对象转化Map
我们在开发的过程中可能会遇到这样的一个场景:我们需要将一个对象中的属性名和值放在一个Map中,当属性比较少的时候你可以选择逐一放,但是如果我们要动态获取指定属性或者属性特别多的时候,这种“笨方法”显然是行不通的,本篇博客提供两种方式:通过反射将对象转化为Map和利用JackJson将对象转化为Map。
通过反射将对象转化为Map
<!--lombok-->
<dependency>
<groupId>org.pr
本文在提供完整代码示例,可见 https://github.com/YunaiV/SpringBoot-Labs 的 lab-55 目录。
原创不易,给点个 Star 嘿,一起冲鸭!
1. 概述
友情提示:MapStruct 和 Spring Boot ...
SpringBoot输出JSON以往使用SpringMVC中开发时,对象转JSON需要配置很多东西
【1】添加FastJson/jackjson等第三方jar
【2】在配置文件中配置Controller扫描
【3】给方法添加@ResponseBody配置FastJson还需要给配置文件中添加(很麻烦( ▼-▼ ))<mvc:annotation-driven>
<mvc:message
public static RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTime.
使用spring的bean工具类:
//org.springframework.beans.BeanUtils包下:
BeanUtils.copyProperties(空实体类对象,目标实体类对象);
apache的公用工具类:也有复制目标实体类的属性到另一个实体类的方法:
//org.apache.commons.beanutils包下
BeanUtilsBean.copyProperties(空实体类对象,目标实体类对象);
在 Java 中,可以使用第三方的工具将 Map 转换为 Java 对象。其中一种常见的方法是使用 Google 的 Gson 库。
首先,你需要在项目中添加 Gson 的依赖。然后,你可以使用 Gson 的 fromJson() 方法将 Map 转换为 Java 对象。例如:
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 30);
Gson gson = new Gson();
Person person = gson.fromJson(gson.toJson(map), Person.class);
System.out.println(person.getName()); // prints "John"
System.out.println(person.getAge()); // prints 30
这里假设你已经有了一个名为 Person 的 Java 类,其中包含名为 name 和 age 的属性。