controller接口返回的数据特殊修订字段

发布时间 2023-12-07 17:28:31作者: 做时间的好朋友

1.对某些字段指定额外的返回值

核心是使用@JsonProperty("cluster_name") 注解来指定接口返回的时候数据解析的字段
@SerializedName注解是gson格式化输出和解析的时候用来解析的

package delta.api.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class EsSlowLogDetail {

    /**
     * 集群名称
     */
    @JsonProperty("cluster_name")
    @SerializedName(value = "cluster_name")
    private String clusterName;


    /**
     * 当前写入记录ID
     */
    @JsonProperty("dataId")
    @SerializedName(value = "dataId")
    private String id;

    /**
     * 索引名称
     */
    private String index;

    /**
     * 日志级别,TRACE,DEBUG,INFO,WARRING,ERROR
     */
    private SlowLogLevel level;

    /**
     * 节点名称,执行当前慢操作的数据节点名称
     */
    @JsonProperty("node_name")
    @SerializedName(value = "node_name")
    private String nodeName;

    /**
     * 路由策略,Index慢日志中记录命中的路由策略
     */
    private String routing;

    /**
     * 搜索方式,Query慢日志中的搜索类型
     */
    private String type;

    /**
     * 搜索命中的分片号
     */
    private String shard;

    /**
     * 请求报文
     */
    private String source;

    /**
     * 结束执行时间,产生日志的容器本地时间(ES version >7 )
     */
    private Long timestamp;

    /**
     * 执行耗时/ms
     */
    @JsonProperty("took_millis")
    @SerializedName(value = "took_millis")
    private Long tookMillis;

    /**
     * 返回行数
     */
    @JsonProperty("total_hits")
    @SerializedName(value = "total_hits")
    private Long totalHits;

    /**
     * 命中分片数
     */
    @JsonProperty("total_shards")
    @SerializedName(value = "total_shards")
    private Integer totalShards;

    /**
     * 当前慢操作影响的类型列表,ES 2 以上的版本type 机制废弃,此字段无效
     */
    private String types;


}

2.controller接口返回给前端的时候对于null的特殊处理

核心是使用@JsonInclude(JsonInclude.Include.NON_NULL) 来过滤null值字段

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class EsSlowLogRecord extends SlowLogRecord {

    @SerializedName(value = "log_content")
    private String logContent;

    private Long time;

    private SlowLogType slowLogType;

    private ResourceCategory resourceCategory;

    @JsonProperty("log_detail")
    @SerializedName(value = "log_detail")
    private EsSlowLogDetail logDetail;

}

如果想达到{}的效果,需要内嵌对象也使用@JsonInclude(JsonInclude.Include.NON_NULL) 修饰到类上

@Data
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EsSlowLogDetail {

}