自定义注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ToJsonField {
/**
* key名
*/
String name() default "";
}
注解使用:
@Data
public class LeaveFormReqDTO {
/**
* 用户id
*/
@Require
public String weaverUserId;
private String leaveStartDate;
private String leaveEndDate;
private String leaveItemName;
private String leaveRecordValue;
private String toExamineCode;
private String flowNumber;
// 是否符合抚恤金发放
@ToJsonField(name = "CN_IF01")
private String CN_IF01;
//是否符合结婚礼金发放
@ToJsonField(name = "CN_IF02")
private String CN_IF02;
//是否符合生育礼金发放
@ToJsonField(name = "CN_IF03")
private String CN_IF03;
//请休假事由
@ToJsonField(name = "CN_ApplyNote")
private String CN_ApplyNote;
}
处理对象的注解使用情况
public static String toCustomJson(Object param) throws IllegalAccessException {
List<Map<String,String>> list = new ArrayList<>();
Class<?> clazz = param.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// 设置true访问实体类中私有属性
field.setAccessible(true);
// 判断是否有使用ToJsonField注解
boolean annotationPresent = field.isAnnotationPresent(ToJsonField.class);
if (annotationPresent) {
Map<String, String> map = Maps.newHashMap();
// 属性名称
String key = field.getName();
if (!StringHelper.isNullOrEmpty(field.getAnnotation(ToJsonField.class).name())) {
// 注解的属性值
key = field.getAnnotation(ToJsonField.class).name();
}
// 获取对象属性的值
String value =(String) field.get(param);
map.put("Key",key);
map.put("Value",value);
if(StringUtils.isBlank(value)){
continue;
}
list.add(map);
}
}
return JsonHelper.toJsonString(list);
}