对象成员变量未序列化

时间:2019-10-09 10:56:39

标签: java jersey jackson2

我有一个类Test,它的成员变量类型为NestedTest

import com.fasterxml.jackson.annotation.JsonView;

class Test{

    String s1;

    @JsonView(ConvertView.class)
    int a;

    @JsonView(ConvertView.class)
    NestedTest nestedObj;
}


class NestedTest{
    int n;
    String s;
}

序列化Test类的对象后,nestedObj字段显示为空。我猜这是因为我禁用了默认视图包含,该默认视图包含也应用于NestedTest对象的字段。如果是这种情况,如何预防呢?我想禁用不包含仅针对外部类而不是对象成员变量的字段的未附加视图的字段。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.MapperFeature;
.........
.........
Test test =new Test();
........
........
ObjectWriter writer = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION).writer();
String s= writer.withView(ConvertView.class).writeValueAsString(test);
System.out.println(s);

我的pom.xml

<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>Inheritance</groupId>
    <artifactId>Inheritance</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

        </plugins>

    </build>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.3</version>
        </dependency>
    </dependencies>
</project>

1 个答案:

答案 0 :(得分:0)

在课程级别为@JsonView指定NestedTest

@JsonView(ConvertView.class)
class NestedTest{
    int n;
    String s;
}

对于自定义类,您需要为树中的每个类指定@JsonView,要在视图中显示哪些字段。