我的控制器中有一个方法,应该返回 JSON 格式的字符串。它返回非原始类型的 JSON:
@RequestMapping(value = "so", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return new ResponseEntity<String>("This is a String", HttpStatus.OK);
}
卷曲响应为:
This is a String
问题的根源在于 Spring(通过 ResponseEntity、RestController 和/或 ResponseBody)将使用字符串的 contents 作为原始响应值,而不是将字符串视为 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 格式化程序,例如 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"));
}
}
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
return "This is a String";
}
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) throws JSONException {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
另一种解决方案是使用
String
的包装器,例如:
public class StringResponse {
private String response;
public StringResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
}
然后在控制器的方法中返回它:
ResponseEntity<StringResponse>