info.baseinsight.core.json.EntitySimpleJsonSerializer Maven / Gradle / Ivy
The newest version!
package info.baseinsight.core.json;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import info.baseinsight.core.SpringUtils;
import info.baseinsight.core.annotation.EntitySimpleJsonFormat;
import jakarta.persistence.Entity;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by @Author:xiaopeng
*自定义的faster JSON输出类 ,读取entity类的注解EntitySimpleJsonFormat的设置
*
*/
public class EntitySimpleJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
Class aclass=jsonGenerator.getCurrentValue().getClass();
EntitySimpleJsonFormat annotation= null;
try {
annotation = aclass.getDeclaredField(jsonGenerator.getOutputContext().getCurrentName()).getAnnotation(EntitySimpleJsonFormat.class);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
if(annotation!=null){
//自定义设置domainjsonformat
List jsonFieldList=new ArrayList();
Class objClass=obj.getClass();
Field[] allFields = objClass.getDeclaredFields();
List needFields=Arrays.stream(annotation.value()).toList();
List ignoreFields=Arrays.stream(annotation.ignores()).toList();
Arrays.stream(allFields).toList().forEach(field->{
if(needFields.contains(field.getName())){
jsonFieldList.add(field);
}
});
Arrays.stream(allFields).toList().forEach(field->{
if(ignoreFields.contains(field.getName())){
jsonFieldList.remove(field);
}
});
if(jsonFieldList.size()>0){
for(Field field : jsonFieldList){
jsonGenerator.writeStartObject();
String methodName="get"+ StringUtils.uncapitalize(field.getName());
Object fieldValue= SpringUtils.doMethod(obj,methodName,new ArrayList