当我使用对象映射器时,它会在响应中包含\ r \ n。帮我解决它。 我有训练POJO,它有字符串名称和字符串值。 我将名称设置为“悉尼”,将值设置为“SYD”。重新运行
{\ \ \"name \" : \"Sydney\",\ \ \"Value \" : \"SYD\",\ \ \"isEnable\" : false,\ \ \"isCurrent\" : false\ \ }"
浏览器中的原始值
"{\r\n \"name\" : \"Sydney\",\r\n \"name\" : \"SYD\",\r\n \"isEnable\" : false,\r\n \"isCurrent\" : false\r\n}"
下面是我的代码 列车
public class Train {
public Train() {
}
private String name;
private String value;
private String Code;
private String countryName;
private String state;
private String stateName;
private boolean isEnable;
private boolean isCurrent;
//*getters and setters/*/
}
控制器calss
public ResponseEntity<String> getDetails( )
throws IOException {
ResponseEntity<String> responseEntity = null;
try(StringWriter writer = new StringWriter()) {
ObjectMapper mapper = new ObjectMapper();
Train train = new Train();
// set name and value to the train object//
if(train != null)
{
mapper.setSerializationInclusion(Inclusion.NON_NULL);
mapper.setSerializationInclusion(Inclusion.NON_EMPTY);
mapper.writerWithDefaultPrettyPrinter().writeValue(writer,
train);
responseEntity = new ResponseEntity<>(writer.toString(),
HttpStatus.OK);
}
}
catch()
{}
return responseEntity;
}
配置:
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
converters.add(extendedJsonConvertor());
super.configureMessageConverters(converters);
}
@Bean
public MappingJackson2HttpMessageConverter extendedJsonConvertor() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter
.setObjectMapper(getNullAndEmptyFilteredObjectMapper());
return mappingJackson2HttpMessageConverter;
}
@Bean
public ObjectMapper getNullAndEmptyFilteredObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
objectMapper.configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
当我调试上面的代码时,我发现mapper包含了响应中的\ r \ n。帮我了解如何删除这些斜杠。
答案 0 :(得分:3)
问题在于以下一行。
mapper.writerWithDefaultPrettyPrinter().writeValue(writer,train);
尝试用
替换它mapper.writeValue(writer,train);
为什么在配置MappingJackson2HttpMessageConverter时会创建一个新的对象映射器?
您可以自动装配对象映射器或返回实际对象,然后让spring将其转换为json
答案 1 :(得分:1)
我认为这是一个“简单”的双重编码问题。您在响应实体中设置一个字符串,该字符串再次写为json响应。
如果你想依赖于spring view rendering(mappingjackson2httpmessageconverter),你必须为“Train”创建一个响应实体。 (或直接从您的控制器方法返回列车实例)
或者你使用实现它的方式,你必须确保为json响应呈现一个字符串不会使用jackson消息转换器,但是春天不会触及它。