我的控制器中有一个方法应该返回JSON中的String.它返回非原始类型的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);
}
Run Code Online (Sandbox Code Playgroud)
卷曲响应是:
This is a String
Run Code Online (Sandbox Code Playgroud)
zac*_*nos 41
问题的根源是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\"");
Run Code Online (Sandbox Code Playgroud)
第一个输出不能解析为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"));
}
}
Run Code Online (Sandbox Code Playgroud)
Nim*_*sky 13
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
return "This is a String";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66902 次 |
| 最近记录: |