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

标签 java spring controller json

我想模拟一些 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/

相关文章:

spring - 使用 spring security 和 mongodb 进行 Rest 身份验证

javascript - 获取所有 Angular Controller

java - 将 ECIES ECP CryptoPP 转换为 JAVA

java - Quartz Scheduler (cron) 能否在同一执行时间调度多个作业?

java - 无法将流输出到浏览器

java - 如何在 java web 中将项目名称添加到 url

java - WebJars 无法在 JSP 中访问

ruby-on-rails - 如何证明 Rails 上 Controller 的简单方法?

asp.net-mvc - MVC - 在 Controller 中处理资源

java - 使用 currentTimeMillis 作为方法