I have a class Test
which has a member variable of type 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;
}
After serializing an object of class Test, the field nestedObj is showing to be null. I am guessing this is because I have disabled default view inclusion which is being applied on fields of NestedTest object as well. If this is the case, how do I prevent it? I want to disable inclusion of fields which doesn't have a view attached to them only for the outer class and not the fields of Object member variables.
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);
My 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>
Specify the @JsonView
on class level for the NestedTest
:
@JsonView(ConvertView.class)
class NestedTest{
int n;
String s;
}
For your custom classes you need to specify the @JsonView
for every class in the tree, which fields you want to make visible, to the view.