Java Spring响应JSON字符串未被转换
我有以下Spring方法:Java Spring响应JSON字符串未被转换,java,json,spring,response,httpresponse,Java,Json,Spring,Response,Httpresponse,我有以下Spring方法: @RequestMapping(value = "/product/{productId}", method = RequestMethod.GET ,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getProductById( //ProductDTO database query in order to retrieve productg
@RequestMapping(value = "/product/{productId}", method = RequestMethod.GET ,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getProductById(
//ProductDTO database query in order to retrieve productg by ID and population
final ObjectMapper objectMapper = new ObjectMapper();
final String json = objectMapper.writeValueAsString(productDTO);
return new ResponseEntity<>(json, HttpStatus.OK);
我需要它在回应中不被逃避,我如何才能做到这一点
我手动转换DTO的原因是,如果我只是在ResponseEntity中返回DTO,Spring处理的JSON表示形式与我使用objectMapper.writeValueAsString方法得到的JSON表示形式不同,而不是得到以下结果:
"name": "nombre de prueba",
"otherProperties": {
"container": false,
"onlineExclusive": false,
"sizeGuide": "size guide",etc..
我明白了:
"name": "nombre de prueba",
"otherProperties": [
{
"key": "container",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "onlineExclusive",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "sizeGuide",
"value": {
"type": "string",
"value": "size guide"
}
},
```
只需返回
ResponseEntity
而不是自己编写字符串,Spring将处理JSON转换。不要添加附加信息作为注释,而是编辑您的问题。您不应该自己进行JSON序列化。Spring将使用预先配置的ObjectMapper
@M.Deinum为您处理这个问题。我已经编辑了这个问题。您能检查一下吗?显然,otherProperties
是一个映射,它的序列化方式不同。不要使用Spring,而是使用框架并根据需要配置默认的ObjectMapper
。如配置所述。您可以通过application.properties
文件中的propreties配置对象映射器。或者,您可能已经意外地使用其他JSON对其进行了重新配置。
"name": "nombre de prueba",
"otherProperties": [
{
"key": "container",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "onlineExclusive",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "sizeGuide",
"value": {
"type": "string",
"value": "size guide"
}
},
```