Jackson json 仅转换选定的字段和方法
Jackson json only convert selected fields and methods
对于 jackson,有一种方法可以使用 @JsonIgnore
忽略某些字段。有没有办法做相反的事情,只显示带注释的字段?我正在使用具有 很多 字段的外部 class,我只想 select 其中的一小部分。我遇到了大量递归问题(使用某种类型的 ORM),其中对象 A -> B -> A -> B -> A .... 甚至不需要导出。
是的,你绝对可以;创建一个仅包含您需要的字段的 class,然后在对象映射器中添加以下 属性,剩下的就完成了。
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false
您可以将对象映射器配置为完全忽略所有内容,除非 JsonProperty
、
指定
public class JacksonConfig {
public static ObjectMapper getObjectMapper(){
//The marshaller
ObjectMapper marshaller = new ObjectMapper();
//Make it ignore all fields unless we specify them
marshaller.setVisibility(
new VisibilityChecker.Std(
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE
)
);
//Allow empty objects
marshaller.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
return marshaller;
}
}
public class MyObject {
private int id;
@JsonProperty
private String name;
private Date date;
//Getters Setters omitted
在这种情况下,只有 name
会被序列化。
示例回购,https://github.com/DarrenForsythe/jackson-ignore-everything
您可以在 pojo class 上使用 @JsonIgnoreProperties(ignoreUnknown=true) 所以只有 pojo 中可用的字段 class 将被映射并且 resf 将被排除在外。
例如
Json数据
{
"name":"Abhishek",
"age":30,
"city":"Banglore",
"state":"Karnatak"
}
pojoclass
@JsonIgnoreProperties(ignoreUnknown=true)
Class Person{
private int id;
private String name;
private String city;
}
Person 中不存在此状态 class,因此不会映射该字段
对于 jackson,有一种方法可以使用 @JsonIgnore
忽略某些字段。有没有办法做相反的事情,只显示带注释的字段?我正在使用具有 很多 字段的外部 class,我只想 select 其中的一小部分。我遇到了大量递归问题(使用某种类型的 ORM),其中对象 A -> B -> A -> B -> A .... 甚至不需要导出。
是的,你绝对可以;创建一个仅包含您需要的字段的 class,然后在对象映射器中添加以下 属性,剩下的就完成了。
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false
您可以将对象映射器配置为完全忽略所有内容,除非 JsonProperty
、
public class JacksonConfig {
public static ObjectMapper getObjectMapper(){
//The marshaller
ObjectMapper marshaller = new ObjectMapper();
//Make it ignore all fields unless we specify them
marshaller.setVisibility(
new VisibilityChecker.Std(
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE,
JsonAutoDetect.Visibility.NONE
)
);
//Allow empty objects
marshaller.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
return marshaller;
}
}
public class MyObject {
private int id;
@JsonProperty
private String name;
private Date date;
//Getters Setters omitted
在这种情况下,只有 name
会被序列化。
示例回购,https://github.com/DarrenForsythe/jackson-ignore-everything
您可以在 pojo class 上使用 @JsonIgnoreProperties(ignoreUnknown=true) 所以只有 pojo 中可用的字段 class 将被映射并且 resf 将被排除在外。
例如
Json数据
{
"name":"Abhishek",
"age":30,
"city":"Banglore",
"state":"Karnatak"
}
pojoclass
@JsonIgnoreProperties(ignoreUnknown=true)
Class Person{
private int id;
private String name;
private String city;
}
Person 中不存在此状态 class,因此不会映射该字段