自定义类继承JsonSerializer


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.fzj.util.SystemConstant;
import com.fzj.exception.ApiException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 自定义JSON 序列化
 * 类型为String 值为null 时 输出 ""
 *
 * @author ZJ.Fang
 * @date 2022/6/29 17:14
 */
@Slf4j
public class MyObjectSerialize<T> extends JsonSerializer<T> {

    @Override
    public void serialize(T obj, JsonGenerator generator, SerializerProvider serializers) throws IOException {
        generator.writeStartObject();
        writeObj(obj, generator);
        generator.writeEndObject();
    }

    private void writeObj(T obj, JsonGenerator generator) throws IOException {
        Field[] fields = ReflectUtil.getFields(obj.getClass());
        for (Field field : fields) {
            if (!ignore(obj, field) && !ignoreNull(obj, field)) {
                generator.writeFieldName(getFieldName(field));
                generator.writeObject(getFieldValue(field, obj));
            }
        }
    }

    private boolean ignoreNull(T obj, Field field) {
        JsonInclude include = field.getAnnotation(JsonInclude.class);
        if (include != null) {
            JsonInclude.Include value = include.value();
            return JsonInclude.Include.NON_NULL.equals(value) && Objects.isNull(ReflectUtil.getFieldValue(obj, field));
        }
        return false;
    }

    private boolean ignore(T obj, Field field) {
        JsonIgnore annotation = field.getAnnotation(JsonIgnore.class);
        Method readMethod = getReadMethod(field, obj);
        return annotation != null || readMethod == null;
    }

    private String getFieldName(Field field) {
        String fieldName;
        JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
        if (jsonProperty != null && StrUtil.isNotBlank(jsonProperty.value())) {
            fieldName = jsonProperty.value();
        } else {
            fieldName = field.getName();
        }
        return fieldName;
    }

    private Object getFieldValue(Field field, Object obj) {
        try {
            Method readMethod = getReadMethod(field, obj);
            if (readMethod == null) {
                return null;
            }

            Object value = readMethod.invoke(obj);
            Object defaultValue = defaultAnnotationValue(field);

            if (value == null && defaultValue != null) {
                return defaultValue;
            } else if (value == null && field.getType().equals(String.class)) {
                return SystemConstant.EMPT_STR;
            } else {
                return value;
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error(e.getMessage(), e);
            throw new ApiException(500, "JSON序列化异常:" + e.getMessage());
        }
    }

    private Object defaultAnnotationValue(Field field) {
        JsonProperty annotation = field.getAnnotation(JsonProperty.class);
        if (annotation == null) {
            return null;
        }
        String s = annotation.defaultValue();
        return convertDefaultValueType(field, s);
    }

    private Object convertDefaultValueType(Field field, String value) {
        return Convert.convert(field.getType(), value);
    }

    private Method getReadMethod(Field field, Object obj) {
        String name = field.getName();
        String getterName = parGetName(name);
        return ReflectUtil.getMethodByName(obj.getClass(), getterName);
    }

    /**
     * 拼接某属性的 get方法
     */
    public static String parGetName(String fieldName) {
        return StrUtil.genGetter(fieldName);
    }

}


使用

@JsonSerialize(using = MyObjectSerialize.class)
public class PersonDTO {
    // Fields、Getter、Setter ...
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐