Spring接口返回转义JSON问题:如何返回未转义JSON?
我来帮你搞定这两个核心问题——手动序列化后JSON被转义,还有直接返回DTO时otherProperties的格式不符合预期。咱们一步步来解决:
一、为什么手动序列化会返回转义后的JSON?
你现在的代码里,把ObjectMapper序列化得到的字符串放进ResponseEntity<Object>返回时,Spring的消息转换器会把这个字符串本身当成普通对象来二次序列化,所以会给字符串加上外层引号,同时转义内部的所有双引号,最终就出现了你看到的转义格式。
如果非要坚持手动序列化(比如需要用自定义的ObjectMapper配置),可以改成返回ResponseEntity<String>,这样Spring会直接把字符串作为响应体输出,不会二次序列化:
@RequestMapping(value = "/product/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getProductById(@PathVariable String productId) throws JsonProcessingException { // 通过数据库查询获取并填充ProductDTO的逻辑 ProductDTO productDTO = productService.getProductById(productId); final ObjectMapper objectMapper = new ObjectMapper(); // 这里可以添加你的自定义序列化配置 final String json = objectMapper.writeValueAsString(productDTO); return new ResponseEntity<>(json, HttpStatus.OK); }
不过这只是临时方案,最优解是让Spring正确序列化你的DTO,既避免转义问题,又能得到你期望的otherProperties格式。
二、让otherProperties序列化成JSON对象而非数组
直接返回DTO时,otherProperties变成了键值对数组,这是因为你的DTO里这个字段是List类型(比如List<PropertyEntry>,每个元素包含key和嵌套的value对象)。要把它转换成期望的JSON对象格式,可以用Jackson的@JsonAnyGetter注解来动态生成属性:
步骤1:修改ProductDTO
假设你的ProductDTO和关联类结构如下:
public class ProductDTO { private String name; // 其他字段... private List<PropertyEntry> otherProperties; // 省略原有getter/setter } // 存储键值对的实体类 public class PropertyEntry { private String key; private PropertyValue value; // getter/setter } // 存储属性值类型和实际值的类 public class PropertyValue { private String type; private Object value; // getter/setter }
给ProductDTO添加一个用@JsonAnyGetter标注的方法,把otherProperties转换成Map:
public class ProductDTO { // 原有字段... private List<PropertyEntry> otherProperties; // 原有getter/setter... // 用@JsonAnyGetter让Jackson把Map的键值对直接作为JSON对象的属性 @JsonAnyGetter public Map<String, Object> getOtherPropertiesAsMap() { Map<String, Object> propertiesMap = new HashMap<>(); for (PropertyEntry entry : otherProperties) { // 取出PropertyValue里的实际值,而非整个嵌套对象 propertiesMap.put(entry.getKey(), entry.getValue().getValue()); } return propertiesMap; } // 忽略原有otherProperties的序列化,避免重复输出 @JsonIgnore public List<PropertyEntry> getOtherProperties() { return otherProperties; } }
步骤2:修改接口直接返回DTO
现在接口可以直接返回ProductDTO,Spring会自动用正确的格式序列化:
@RequestMapping(value = "/product/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ProductDTO> getProductById(@PathVariable String productId) { // 通过数据库查询获取并填充ProductDTO的逻辑 ProductDTO productDTO = productService.getProductById(productId); return new ResponseEntity<>(productDTO, HttpStatus.OK); }
这样返回的JSON就会和你期望的一致:
{ "name": "nombre de prueba", "otherProperties": { "container": false, "onlineExclusive": false, "sizeGuide": "size guide" // ...其他属性 } }
内容的提问来源于stack exchange,提问作者Nexussim Lements

