roeygol
roeygol

Reputation: 5048

How to change message field format for ResponseEntity?

In my Spring-Boot app, my API returns response body using 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"
    }

I need to change the message field format to a shorten format.

I tried to find it over the web and I found references for other 3rd party lib and not for spring.

In my app I got this Configuration 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;
    }
}

Is there a way to format the message field ?

Upvotes: 2

Views: 554

Answers (1)

Vinay Prajapati
Vinay Prajapati

Reputation: 7514

You can write a custom json serializer in jackson and decide what should be done with particular string value by annotation bean property with @JsonSerialize(using=SerializerClassName.class)

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) + "...");
        }
    }
}

Upvotes: 2

Related Questions