Reputation: 7413
I am using fasterxml jackson for json serialization. I have written date serializer as
public class DateObjectSerializer extends JsonSerializer<Date> {
public static final String DATE_FORMAT = "dd.MM.yyyy";
@Override
public void serialize(Date date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
System.out.println("From DateObjectSerializer");
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = dateFormat.format(date);
jgen.writeString(formattedDate);
}
}
But it is not being invoked. However other Jackson Serializers are working fine.
So I added following configuration in application.yaml
spring:
jackson:
serialization-inclusion: non_null
date-format: dd.MM.yyyy
But it din't work.
So I have added this code in SpringBootConfiguration class.
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).setDateFormat(dateFormat);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
Now dates are being serialized correctly. But now valid JSON equivalent strings are not being transformed to JSON as mentioned here.
@RestController
public class SampleController {
@RequestMapping(value = "/jsonInfo", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
public String jsonInfo() {
String string = "{\"name\": \"foo\"}"
return string;
}
}
Upvotes: 1
Views: 3356
Reputation: 314
Try this
import com.fasterxml.jackson.databind.ObjectMapper;
:
@Autowired
private ObjectMapper objectMapper;
@RestController
public class SampleController {
@RequestMapping(value = "/jsonInfo", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
public JsonNode jsonInfo() throws JsonProcessingException, IOException {
String string = "{\"name\": \"foo\"}"
return objectMapper.readTree(string);
}
}
Upvotes: 2