java - 如何更改 ResponseEntity 的消息字段格式?

标签 java spring format httpresponse

在我的 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/

相关文章:

java - Oracle下大交易如何处理?

java - 在 Spring MVC 中哪里存储请求特定值?

c++ - QTextStream格式问题

java - 如果发现重复项,则替换数组中的数字

java - Java中一个对象可以创建多个线程吗

java - 如果为 @Cacheable 调用缓存,则为 Spring 日志

matlab - 将矩阵保存到文件时如何控制格式?

mysql - 格式和圆形mysql的区别

java - Jersey 2 : My ApplicationEventListener is being ignored. 如何解决此问题?

java - 在完成()之后从 Activity 中获取结果;在 Android 单元测试中