@JSonIgnore的等效代码设置

nic*_*man 5 java serialization json jackson json-serialization

我是Java和Jackson的新手以及我尝试使用的许多其他技术,所以我会给出一个详细的答案.

有没有办法阻止一个或多个字段使用Jackson序列化为JSon String_like格式,但没有使用任何类型的JSon注释?

像mapper.getSerializationConfig()之类的东西.某事(忽略("displayname"))如果你知道我的意思.我的对象是一个扩展另一个类的类的实例,并且实现了一个接口,所以这些字段来自类的层次结构.我需要该对象的JSon表示,但只包含某些字段,因此我可以通过POST方法在模拟请求中发送该Json.我正在使用Jackson 2.2.2.提前致谢.

Mic*_*ber 5

如果您无法更改类,则可以创建新的抽象类/接口,该接口将包含带注释的方法abstract class.在此类/接口中,您可以定义interface在序列化/反序列化过程中应跳过的方法.

请看我的小例子:

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws IOException {
        Person person = new Person();
        person.setId(1L);
        person.setName("Max");

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.addMixIn(Person.class, PersonMixIn.class);

        System.out.println(objectMapper.writeValueAsString(person));
    }
}

abstract class Entity {

    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

interface Namamble {
    String getName();
}

class Person extends Entity implements Namamble {

    private String name;

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

interface PersonMixIn {
    @JsonIgnore
    String getName();
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 回答评论

你可以创建这样的mixin接口:

public static interface UserInformationMixIn {
    @JsonIgnore
    String getField3();
}
Run Code Online (Sandbox Code Playgroud)

@JsonIgnore以这种方式配置:

objectMapper.addMixInAnnotations(UserInformation.class, UserInformationMixIn.class);
Run Code Online (Sandbox Code Playgroud)

完整示例源代码:

objectMapper.addMixIn(UserInformation.class, UserInformationMixIn.class);
Run Code Online (Sandbox Code Playgroud)

有用的链接:

  • 我查了一下,但我需要15点声望才能投票,对不起.也许我可以在以后获得更多声望点时做到.非常感谢再次. (2认同)