4

我想从服务器返回一个静态 .json 文件。不仅为了测试目的,我想将 json 文件定义为资源文件(比如 data.json),这样我就可以轻松地对其进行修改。

我已经这样做了,将 data.json 放在资源目录中并指定资源映射:

<resources mapping="/resources/**" location="/resources/" />

我的问题是,当返回 data.json 时,内容类型是application/octet-stream,而我希望它是application/json。我该如何指定?

此外,在我的控制器中,我有一些方法返回一个字符串(例如home),这些方法通过以下方式自动映射到 jsp InternalResourceViewResolver

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

我怎样才能对 .json 资源做同样的事情(显然没有 jsp 编译过程)?

4

4 回答 4

2

我认为在您的 web.xml 中您可以添加以下内容:

<mime-mapping>
  <extension>json</extension>
  <mime-type>application/json</mime-type>
</mime-mapping>

我相信这将指示 Web 容器将 application/json mime 类型应用于以 .json 扩展名提供服务的任何文件。

于 2013-06-07T11:08:24.317 回答
2

重新审视一个较旧的问题,只是为了提供一个更新的答案。以下代码段应该是不言自明的:

@RestController
public class JsonController {

@GetMapping(value = "/file", produces = MediaType.APPLICATION_JSON_VALUE)
public String defaultQuiz() {
    Resource resource = new ClassPathResource("data.json");
    String json = "";
    try(InputStream stream = resource.getInputStream()) {
        json = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
    } catch (IOException ioe) {
        throw new YourCustomRuntimeException(ioe.getMessage(), ioe);
    }
    return json;
  }
 }
于 2018-10-26T08:26:31.277 回答
1

我做到了这一点。

@GetMapping(value = "/my-endpoint",
    produces = MediaType.APPLICATION_JSON_VALUE)
public String fetchJson() {
    String json = "";
    try(InputStream stream = getClass().getResourceAsStream("/my-static-json.json")) {
        json = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
    } catch (IOException ioe) {
        log.error("Couldn't fetch JSON! Error: " +
                ioe.getMessage());
    }
    return json;
}

注意:JSON 文件位于 src/main/resources 下

于 2021-04-11T10:26:11.190 回答
0

您可以通过添加@ResponseBody请求的控制器方法从控制器发送响应作为 jSON 字符串,例如:

public @ResponseBody String getJsonDetails(){

return object; // object may be your list of object(which will send response as JSON) or simple json string
}

您需要通过在 spring-context xml 文件中添加以下 bean 来配置它:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
         <map>
            <entry key="html" value="text/html"/>
            <entry key="json" value="application/json"/>
        </map>
        </property>

        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                    <property name="prefixJson" value="true"/>
                </bean>
            </list>
        </property>
    </bean>
于 2013-06-07T11:04:05.120 回答