问题的根源在于 Spring(通过ResponseEntity、RestController和/或ResponseBody)将使用字符串的内容作为原始响应值,而不是将字符串视为要编码的 JSON 值。即使在控制器方法使用时也是如此produces = MediaType.APPLICATION_JSON_VALUE
,就像这里的问题一样。
它本质上就像以下之间的区别:
// yields: This is a String
System.out.println("This is a String");
// yields: "This is a String"
System.out.println("\"This is a String\"");
第一个输出不能解析为 JSON,但第二个输出可以。
然而,类似的东西'"'+myString+'"'
可能不是一个好主意,因为它不会处理字符串中双引号的正确转义,并且不会为任何此类字符串生成有效的 JSON。
处理此问题的一种方法是将字符串嵌入到对象或列表中,这样您就不会将原始字符串传递给 Spring。但是,这会改变您的输出格式,如果这是您想要做的,实际上没有充分的理由不能返回正确编码的 JSON 字符串。如果这是您想要的,最好的处理方法是通过 JSON 格式化程序,例如Json或Google Gson。以下是 Gson 的外观:
import com.google.gson.Gson;
@RestController
public class MyController
private static final Gson gson = new Gson();
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return ResponseEntity.ok(gson.toJson("This is a String"));
}
}