在Java中使用Jackson的@JsonView注释的重要性?
JsonView 注释 可用于包含/排除期间动态序列化和反序列化过程的性质。我们需要配置一个ObjectMapper 类,以包括用于使用writerWithView()方法从Java对象编写JSON的视图类型。
语法
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonView示例
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonViewAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());
String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());
System.out.println(jsonString);
System.out.println(jsonStringInternal);
}
}
//人类
class Person {
@JsonView(Views.Public.class)
public long personId = 115;
@JsonView(Views.Public.class)
public String personName = "Raja Ramesh";
@JsonView(Views.Internal.class) public String gender = "male";
@Override
public String toString() {
return "Person{" +
"personId=" + personId +
", personName='" + personName + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
class Views {
static class Public {}
static class Internal extends Public {}
}输出结果
{"personId":115,"personName":"Raja Ramesh"}
{"personId":115,"personName":"Raja Ramesh","gender":"male"}