从 Spring Controller 中的文件 (JSONObject) 返回模拟的 JSON

Nam*_*mek 4 java spring json controller jsonobject

我想模拟一些 JSON(我正在从文件中读取),并将其作为某些 Spring Controller 的结果返回。

文件中当然包含正确的 JSON 数据格式,例如:

{"country":"","city":""...}
Run Code Online (Sandbox Code Playgroud)

我的控制器看起来像:

@RestController
@RequestMapping("/test")
public class TestController {

    @Value("classpath:/META-INF/json/test.json")
    private Resource testMockup;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONObject getTest() throws IOException {
        JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
        return jsonObject;
    }
}
Run Code Online (Sandbox Code Playgroud)

读取文件本身等jsonObject本身没有问题, 调试 PoV 是正确的,但是我从浏览器获取HTTP 状态 406。我也试过只返回 String (通过返回jsonObject.toString()),而不是JSONObject. 然而,它会导致编码问题 - 因此来自浏览器的 JSON 不是 JSON 本身(一些额外的斜杠、引号等)。

有什么办法可以从文件中返回 JSON?

Hei*_*erg 6

这对我有用。

爪哇:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@RestController("/beers")
public class BeersController {

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    Object getBeers() {
        Resource resource = new ClassPathResource("/static/json/beers.json");
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(resource.getInputStream(), Object.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

科特林:

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.core.io.ClassPathResource
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/beers")
class BeersController {

    @GetMapping
    fun getBeers(): Any? {
        val resource = ClassPathResource("/static/json/beers.json")
        return ObjectMapper().readValue(resource.inputStream, Any::class.java)
    }

}
Run Code Online (Sandbox Code Playgroud)


The*_*ush 0

这不是无效的 JSON。如果不是拼写错误,请尝试重新格式化您的文件,使其看起来像

{"country":"","city":""}
Run Code Online (Sandbox Code Playgroud)

请注意属性名称周围的开头引号。