Jackson json仅转换选定的字段和方法

问题描述

使用杰克逊,可以使用@JsonIgnore忽略某些字段。有没有办法做相反的事情,只显示带有注释的字段?我正在与具有很多字段的外部类一起工作,我只想选择其中的一小部分。我遇到了很多递归问题(使用某种类型的ORM),其中对象A-> B-> A-> B-> A ....甚至不需要导出。

解决方法

是的,您当然可以;创建一个仅包含所需字段的类,然后在对象映射器中添加以下属性,其余的操作就完成了。

DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false
,

您可以将对象映射器配置为完全忽略所有内容,除非 >>> df = pd.DataFrame({'user': ['Ticket ID','Closed Time','Tags'],... 'income': [1,2,3,],... 'Closed Time': ['08/19/20','08/18/20','08/17/20'],... 'Tags': [270201,284912,123456789101]}) >>> separate_row(df,"Tags") user income Closed Time Tags 0 Ticket ID 1 08/19/20 270201 1 Closed Time 2 08/18/20 284912 2 Tags 3 08/17/20 123456 3 Tags 3 08/17/20 789101 >>> df = pd.DataFrame({'user': ['Ticket ID',123456789101123456]}) >>> separate_row(df,"Tags") user income Closed Time Tags 0 Ticket ID 1 08/19/20 270201 1 Closed Time 2 08/18/20 284912 2 Tags 3 08/17/20 123456 3 Tags 3 08/17/20 789101 4 Tags 3 08/17/20 123456 指定

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
        )
    );

    //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 会被序列化。

示例回购,https://github.com/DarrenForsythe/jackson-ignore-everything

,

您可以在pojo类上使用 @JsonIgnoreProperties(ignoreUnknown = true),以便仅映射pojo类中可用的字段,而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类中,因此不会映射该字段