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

时间:2019-10-03 11:26:03

标签: 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"
    }

我需要将消息字段格式更改为短格式。

我试图在网上找到它,但发现了其他第三方库的引用,而不是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;
    }
}

是否可以格式化消息字段?

1 个答案:

答案 0 :(得分:2)

您可以在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) + "...");
        }
    }
}