Java 获取类中所有字段 转换为 json字符串 Java 类中字段转换为json字符串 javabean 字段 转换为 jsonStr
一、概述
最近开发工作中,需要将类中的所有字段获取出来,并转换为json字符串,予以存储起来,用于poi excel导出,可以根据实际需要,增、减字段,来调整导出列的需求。 本文将 使用 反射的方式,获取类中的字段,存储到map中,再使用Fastjson转换为json字符串,用于输出存储。
二、代码实现
1、依赖 pom
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、代码
/**
* Description: 生成类的字段 映射 map
* @param clz 转换类的 class 对象
* @param excludeList 排除的字段名
* @param clzAnon 注解名 --- 用于字段 注释信息获取
* @return java.util.List<java.util.Map<java.lang.String,java.lang.String>>
* @version v1.0
* @author wu
* @date 2022/9/26 21:04
*/
public <T> List<Map<String, String>> getPropertyMap(Class<T> clz, List<String> excludeList, Class<? extends Annotation> clzAnon) {
List<Field> fieldList = Arrays.stream(clz.getDeclaredFields()).collect(Collectors.toList());
List<Map<String, String>> mapList = Lists.newArrayList();
int n = 1;
for (Field f : fieldList) {
String name = f.getName();
if (CollectionUtils.isNotEmpty(excludeList)) {
if (excludeList.contains(name)) continue;
}
HashMap<String, String> tempMap = Maps.newHashMap();
Annotation annotation = f.getAnnotation(clzAnon);
String colName = name;
if (annotation instanceof ApiModelProperty) {
ApiModelProperty a = (ApiModelProperty) annotation;
colName = a.value();
}
// add more Annotation support ...
tempMap.put("colIndex", "" + n ++);
tempMap.put("colName", colName);
tempMap.put("property", name);
mapList.add(tempMap);
}
return mapList;
}
3、测试
@Test
public void genPropertyMap(){
ArrayList<String> list = Lists.newArrayList();
list.add("num22"); // 过滤掉属性num22
List<Map<String, String>> propertyMap = getPropertyMap(Child.class, list, ApiModelProperty.class);
System.out.println("propertyMap: \n"+ JSON.toJSONString(propertyMap));
}
3.1、输出结果如下:
propertyMap:
[
{
"colIndex": "1",
"colName": "id2号",
"property": "id22"
},
{
"colIndex": "2",
"colName": "名字2号",
"property": "name22"
},
{
"colIndex": "3",
"colName": "地址2号",
"property": "addr22"
}
]
4、补充:Child 类结构如下
public class Child {
@ApiModelProperty(value = "id2号")
public int id22 ;
@ApiModelProperty(value = "数字2号")
protected int num22 ;
@ApiModelProperty(value = "名字2号")
String name22 ;
@ApiModelProperty(value = "地址2号")
private String addr22;
// ignore getter/setter
}
三、总结
1、获取一个类中的所有字段,可以使用反射来实现; 转换json字符串,可以使用 Fastjson、Gson、Jackson 等工具类实现 ..
2、关于反射,注解等相关的知识,可以参考:
- Java反射 getFields和 getDeclaredFields 方法的区别_HaHa_Sir的博客-优快云博客_getfields
- java 反射多级调用实现原理 java EL表达式多级调用实现原理_HaHa_Sir的博客-优快云博客
- java Introspector内省和Reflect反射学习、联系和区别_HaHa_Sir的博客-优快云博客
3、idea 方法注释模板设置: Idea 设置方法注释模板 Idea 2021.2配置方法类注释模板_HaHa_Sir的博客-优快云博客_idea设置方法注释模板