此方法并无实际作用,主要是为了加深对反射以及注解的理解,实现字段不被序列化的方法是获取添加注解的属性名称,然后使用正则替换。
实体类
@Data
public class User {
private int id;
@UnSerialize
private String name;
@UnSerialize
//忽略序列化
private Integer age;
@UnSerialize
private String sex;
private String password;
}
自定义注解
@Target( ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnSerialize{
}
工具类
public class Utils {
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* 将对象转化为json字符串
* @param o
* @return
* @param <T>
* @throws JsonProcessingException
*/
public static <T> String objectToJsonStr(T o) throws JsonProcessingException {
String jsonStr = objectMapper.writeValueAsString(o);
Class<?> oClass = o.getClass();
//获取所有属性
Field[] fields = oClass.getDeclaredFields();
int i = 1;
for(Field field : fields){
//获取属性上的所有注解
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
//如果注解有取消序列化的注解,则移除属性
if (annotation.annotationType()==UnSerialize.class) {
String regx = (i==1?"":",")+"\""+field.getName()+"\":.*?(?=}|,)";
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(jsonStr);
jsonStr = matcher.replaceAll("");
}
}
i++;
}
if (jsonStr.charAt(1)==',') jsonStr = jsonStr.replaceFirst(",","");
return jsonStr;
}
/**
* 序列化对象,将普通对象转化为字符串
* @param f 自定义序列化方法
* @param o 对象
* @return
* @param <T>
* @throws JsonProcessingException
*/
public static <T> String objectToJsonStr(Function<T,String> f,T o) throws JsonProcessingException {
if (f==null) return objectToJsonStr(o);
return f.apply(o);
}
public static <T> T jsonStrToObject(String jsonStr,Class<T> Class) throws JsonProcessingException {
Field[] fields = Class.getDeclaredFields();
jsonStr = getString(jsonStr, fields);
int i = 1;
for(Field field : fields){
//获取属性上的所有注解
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
//如果注解有取消序列化的注解,则移除属性
if (annotation.annotationType()== UnSerialize.class) {
String regx = (i==1?"":",")+"\""+field.getName()+"\":.*?(?=}|,)";
// System.out.println(regx);
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(jsonStr);
jsonStr = matcher.replaceAll("");
}
}
i++;
}
if (jsonStr.charAt(1)==',') jsonStr = jsonStr.replaceFirst(",","");
return objectMapper.readValue(jsonStr,Class);
}
}
测试方法
public static void main(String[] args) throws JsonProcessingException {
User user = new User();
user.setName("张三");
user.setAge(10);
user.setSex("男");
user.setId(10);
user.setPassword("uihgsfui");
String userJson = objectToJsonStr(user);
System.out.println(userJson);
User user1 = jsonStrToObject(userJson, User.class);
System.out.println(user1);
}
结果
实现的添加自定义注解@UnSerialize的属性不被序列化和反序列化,但本注解并无实际作用,可以使用jackson中的@JsonIgnore注解来实现此效果。