json只转换选定的字段和方法

wtlkbnrh  于 2021-07-12  发布在  Java
关注(0)|答案(3)|浏览(316)

对于jackson,有一种方法可以忽略使用 @JsonIgnore . 有没有相反的方法,只显示带注解的字段?我正在处理一个有很多字段的外部类,我只想选择其中的一小部分。我得到了大量的递归问题(使用某种类型的orm),其中对象a->b->a->b->a。。。。甚至不需要出口。

vsikbqxv

vsikbqxv1#

可以将对象Map器配置为完全忽略所有内容,除非 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

xdnvmnnf

xdnvmnnf2#

当然可以;创建一个只包含所需feild的类,并在对象Map器中添加下面的属性,剩下的就完成了。

DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false
rbpvctlc

rbpvctlc3#

您可以在pojo类上使用@jsonignoreproperties(ignoreunknown=true),这样就只Mappojo类中可用的字段,而忽略resf。
例如
json数据

{
"name":"Abhishek",
"age":30,
"city":"Banglore",
"state":"Karnatak"
}

pojo类

@JsonIgnoreProperties(ignoreUnknown=true)
Class Person{
   private int id;
   private String name;
   private String city;
}

此处状态在person类中不存在,因此该字段不会被Map

相关问题