Springboot手持JSON到前端
我希望根据请求将JSON传递给客户端。我的实际代码如下所示:Springboot手持JSON到前端,json,spring-boot,request-mapping,Json,Spring Boot,Request Mapping,我希望根据请求将JSON传递给客户端。我的实际代码如下所示: ... import org.apache.commons.io.IOUtils; import org.springframework.core.io.Resource; ... @RestController public class Controller { @Value("classpath:file.json") private Resource jsonFile; @GetMapping(pa
...
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
...
@RestController
public class Controller {
@Value("classpath:file.json")
private Resource jsonFile;
@GetMapping(path ="json", produces = "application/json")
public String getJSON() {
try (InputStream in = jsonFile.getInputStream()) {
return IOUtils.toString(in, StandardCharsets.UTF_8.name());
}
catch ...
}
}
...
jsonFile是.json文件,我想将其内容发送回用户,@Value注释添加类路径
问题是:响应不仅是json,而且换行符被编码为\n
,整个json被封装在引号中,使其成为一个大字符串而不是一个对象。由于JSON实际上是一个.JSON文件,我不想首先将其解析为一个对象
jsonFile看起来像:
{
"thing1": [
{
"list1": [
"abc"
],
"subthing1": {
"list1": [
"aaa",
"bbb"
],
"list2": [
"ccc"
],
"list3": [
"zzz"
],
},
"subthing2":
...
编辑1:的答案最后一段指出“如果您想返回json序列化字符串,那么只需返回该字符串即可”。这对我来说是红色的:“如果字符串中有json,请返回字符串”使用wriper for string:
class StringRespWriper {
private String stringResponse;
// get/set
}
并将其返回到控制器上:
@GetMapping(path ="json", produces = "application/json")
public StringRespWriper getJSON() {
try (InputStream in = var.getInputStream()) {
....
}
什么是var?声明在哪里?您可能想检查一下您得到的字符串,因为您的代码是这样说的。i、 e返回IOUtils.toString(in,StandardCharsets.UTF_8.name());请解释代码中的var是什么。对不起,没有看到您遗漏的信息,希望这是您要求的信息?还修复了错误为ät.RequestController的类注释不是正确的ät.RestController