简体   繁体   中英

return empty value for property during json serialization

I have a class in java that contains sensitive data therefore I want to omit only the properties value when exporting the data. Although Property name should still be available in the JSON.

Example:

private String id;
private String username;
private String password;

how can I only make password to go empty. rather than disappearing the whole property,

{"id":"asdasd0123213", "username":"smith", password: ""}

Use annotation @JsonSerialize for password field and create CustomSerialize class. Or create method:

@JsonGetter("password")
public String getEmptyPassword() {
    return "";
}

You can solve it without Custom serializer also. Quick example:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class JacksonTest {
    private String id;
    private String username;
    @JsonIgnore
    private String password;

    @JsonProperty("password")
    public String getPassword() {
        return "";
    }

    @JsonProperty("password")
    public void setPassword(String password) {
        this.password = password;
    }

    @JsonIgnore
    public String getPasswordValue() {
        return password;
    }

    @Override
    public String toString() {
        return "JacksonTest{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Sample method to test:

  public static void main(String[] args) throws JsonProcessingException {
            System.out.println(new JacksonTest("id1","user1","pass"));
            System.out.println((new ObjectMapper()).writeValueAsString(new JacksonTest("id1","user1","pass")));
            String json ="{\"id\":\"id1\",\"username\":\"user1\",\"password\":\"test\"}";
            System.out.println((new ObjectMapper()).readValue(json,JacksonTest.class));
        }

The gist is ignore the property using @JsonIgnore and put a custom setter and getter for that property so jackson will use these methods at serialization and deserialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM