我想模拟一些 JSON(我正在从文件中读取),并将其作为某些 Spring Controller 的结果返回。
文件中当然包含正确的 JSON 数据格式,例如:
{"country":"","city":""...}
我的 Controller 看起来像:
@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;
}
}
读取文件本身等没有问题。
jsonObject
本身在调试 PoV 时是正确的,但是我从浏览器中得到 HTTP Status 406。
我也试过只返回字符串(通过返回 jsonObject.toString()
),而不是 JSONObject
。
然而,它会导致编码问题 - 因此来自浏览器的 JSON 不是 JSON 本身(一些额外的斜杠、引号等)。
有什么方法可以从文件中返回 JSON 吗?
最佳答案
这对我有用。
Java:
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;
}
}
Kotlin :
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)
}
}
关于java - 在 Spring Controller 中从文件 (JSONObject) 返回模拟的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595432/