在写过程中如何告诉Jackson ObjectWriter忽略类成员

时间:2018-08-02 14:40:45

标签: java jackson

我正在使用Java。

我有以下课程:

class MyClass{
    @JsonProperty("test")
    String test;

    String myPrivateTest;
}

我正在使用Jackson ObjectWriter将JSON对象写入文件/作为字符串,如下所示:

ObjectWriter writer = objMapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File(path), myObject);

我只想写入文件test而不是myPrivateTest文件,我该怎么做?

编辑

我已经尝试过:

class MyClass{
        @JsonProperty("test")
        String test;

        @JsonIgnore
        String myPrivateTest;
    }

还有

@JsonIgnoreProperties({"myPrivateTest"})
class MyClass{
    @JsonProperty("test")
    String test;

    String myPrivateTest;
}

并且仍然将myPrivateTest写入文件

2 个答案:

答案 0 :(得分:0)

您可以通过提供PropertyFilter来忽略特定字段,如下所示:

@JsonFilter("someFilter")
@Data // lombok
@NoArgsConstructor // lombok
class SomeClass {
    private String name;
    private int someField;

    public SomeClass(String name, int sf){ 
        this.name=name;
        this.someField = sf;
    }
}

@Test
    public void test() throws JsonProcessingException {
        SomeClass someClass = new SomeClass("test",1);
        ObjectMapper mapper = new ObjectMapper();

        PropertyFilter theFilter = new SimpleBeanPropertyFilter() {
            @Override
            public void serializeAsField
                    (Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
                    throws Exception {
                if (include(writer)) {
                    // here you can define the properties to ignore
                    if (!writer.getName().equals("name")) {
                        writer.serializeAsField(pojo, jgen, provider);
                        return;
                    }
                } else if (!jgen.canOmitFields()) {
                    writer.serializeAsOmittedField(pojo, jgen, provider);
                }
            }
        };

        FilterProvider filters = new SimpleFilterProvider()
                .addFilter("someFilter", theFilter);

        String objAsString = mapper
                .writer(filters)
                .writeValueAsString(someClass);

        assertThat(objAsString).doesNotContain("name");
    }

序列化输出为:

{"someField":1}

答案 1 :(得分:0)

使用Jackson 2.9.6

只需将@JsonProperty添加到所需的字段中即可。

public class MyClass {

    @JsonProperty("test")
    String test;

    String myPrivateTest;

    public static void main(String[] args) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        MyClass c = new MyClass();
        c.test = "HELLO";
        c.myPrivateTest = "WORLD";
        System.out.println(objectMapper.writeValueAsString(c));
    }
}

输出:

{"test":"HELLO"}

String myPrivateTest被正确忽略