在我的 Spring-Boot 应用程序中,我的 API 使用 org.springframework.http.ResponseEntity
返回响应正文
Example:
{
"timestamp": "Oct 2, 2019 3:24:32 PM",
"status": 200,
"error": "OK",
"message": "Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool",
"path": "/a/b/c/d/init"
}
我需要将消息字段格式更改为缩短格式。
我试图通过网络找到它,我找到了其他第 3 方库的引用,而不是 spring 的引用。
在我的应用程序中,我得到了这个配置 Bean:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.DateFormat;
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
objectMapper.setDateFormat(DateFormat.getDateTimeInstance());
return objectMapper;
}
}
有没有办法格式化消息字段?
最佳答案
您可以在 jackson 中编写自定义 json 序列化程序,并通过使用 @JsonSerialize(using=SerializerClassName.class) 注释 bean 属性来决定对特定字符串值执行哪些操作
public class Message{
@JsonSerialize(using=MessageSerializer.class)
private String description
//other properties
}
public class MessageSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if(value.length() > 70){
gen.writeString(value.substring(0, 67) + "...");
}
}
}
关于java - 如何更改 ResponseEntity 的消息字段格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218173/