gpt4 book ai didi

java - Jackson 对象映射器在响应中包含转义序列

转载 作者:搜寻专家 更新时间:2023-11-01 02:43:30 24 4
gpt4 key购买 nike

当我使用对象映射器时,它会在响应中包含\r\n。请帮助我如何解决它。我正在训练 POJO,它有字符串名称和字符串值。我将名称设置为“Sydney”,并将值设置为“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/*/
}

Controller 类

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;
}

当我调试上面的代码时,我开始知道映射器在响应中包含那些\r\n 。帮助我如何删除那些斜杠。

最佳答案

问题出在下面这一行。

mapper.writerWithDefaultPrettyPrinter().writeValue(writer,train);  

尝试将其替换为

mapper.writeValue(writer,train);

为什么在配置的时候要新建一个对象映射器,MappingJackson2HttpMessageConverter?
您可以 Autowiring 对象映射器或返回实际对象并让 spring 将其转换为 json

关于java - Jackson 对象映射器在响应中包含转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com