json - Jackson @JsonView 没有按预期工作

标签 json spring spring-mvc jackson

我将 Jackson JSON 1.9.12 与 SpringMVC 一起使用。我创建了一个带有 JSON 字段的 dto。我想要两个具有不同 JSON 字段的相同 dto 配置文件,因此我创建了两个接口(interface)并使用 @JsonView 注释字段注解。

class Views {
    static class Public {}
    static class ExtendedPublic {}
    ...
}

public class Thing {
    @JsonView(Views.Public.class) Integer id;
    @JsonView(Views.ExtendPublic.class) String name;
}

在 Controller 中
@RequestMapping(value = "/thing/{id}")
public void getThing(@PathVariable final String id, HttpServletResponse response) {
    Thing thing = new Thing();
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writerWithView(Views.Public.class).writeValueAsString(thing);
    LOG.debug("JSON: {}", json);
}

我希望 JSON 只包含“id”字段,但它总是包含所有字段。

有任何想法吗?

最佳答案

以下代码使用 Spring 3.2.0 和 Jackson 1.9.12 进行测试,仅返回 {id: 1}而不是扩展的 {name: "name"}因为它使用 .writerWithView(Views.Public.class)。切换到 Views.ExtendPublic.class 将导致 {"id":1,"name":"name"}
编辑:添加所有项目文件以获得完整的解决方案,使其成为比我在 Using @JsonView with Spring MVC 上的另一个更好的答案

DemoController.java

package com.demo.app;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.codehaus.jackson.map.annotate.JsonView;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class DemoController {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value="/jsonOutput")
    @ResponseBody
    public String myObject(HttpServletResponse response) throws IOException {
        ObjectWriter objectWriter = objectMapper.writerWithView(Views.Public.class);
        return objectWriter.writeValueAsString(new MyObject());
    }

    public static class Views {
        static class Public {}
        static class ExtendPublic extends Public {}
    }

    public class MyObject {
        @JsonView(Views.Public.class) Integer id = 1;
        @JsonView(Views.ExtendPublic.class) String name = "name";
    }
}

web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"/>

初始化程序.java
package com.demo.app.spring;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.*;

public class Initializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
        mvcContext.register(AppConfig.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(mvcContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }
}

AppConfig.java
package com.demo.app.spring;

import org.springframework.context.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.demo.app")
public class AppConfig {
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>app</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>${project.artifactId}</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.2.0.RELEASE</spring.version>
        <jetty.plugin.version>8.1.7.v20120910</jetty.plugin.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.12</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.plugin.version}</version>
                <configuration>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

在以下结构中:
pom.xml
src
  |- main
      |- java
      |    |- com
      |        |- demo
      |             |- app
      |                 |- controller/DemoController.java
      |                 |- spring/AppConfig.java, Initializer.java
      |- webapp
           |- WEB-INF/web.xml

关于json - Jackson @JsonView 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973141/

相关文章:

java - Spring Rest API 最大大小 HTTP POST

java - 使用 spring batch 3.0.0 jar 时 'JOB_CONFIGURATION_LOCATION' 中的未知列 'field list'

java - JSON反序列化,不匹配

java - 如何进行单元测试来测试我的 Spring/OSGi 配置?

spring - 移动并重命名 IntelliJ IDEA 的默认 application-config.xml 后出现“未为此文件配置应用程序上下文”错误

java - 是否可以使用 session ID 使来自另一个 session 的 httpsession 无效?

mysql - 出于机器学习目的存储多个来源的数据的最佳实践

php - 按观众数量对 PHP 数组进行排序

json - 如何使用Powershell修改Json

javascript - jQuery - 填充对象中缺失的星期几值