0

A packing class for restful controller return ,has three member variable: code, msg, data.Statement class of data is Object.data may be any entity class.Some members of entity should not appear in the return Json.Is there some way to config ?

I had know @JsonView upon a interface and get method can control whether member appear.But it controll code, msg, data not the member in data.Controller method return Result class like this

public class Result{
  private String code;
  private String msg;
  private User user;
}


public class User {
 private String userName;
 private String password;
}

I expect the result Json without password like this

{
  "code":1,
  "msg":"",
  "data":{
    "userName":"Ted"
   }
}

not like

{
  "code":1,
  "msg":"",
  "data":{
    "userName":"Ted",
    "password":"Tedisbear"
  }
}
Ted.Xiong
  • 1
  • 1

2 Answers2

0

One way to do it is to add the @JsonIgnore annotation to the password field

public class User {
    private String userName;
    @JsonIgnore
    private String password;
}

That way it will never be part of the response.

You could also annotate the getPassword() method and get the same result.

Misantorp
  • 2,606
  • 1
  • 10
  • 18
0

With the default serialization of Spring Boot (using Jackson), there are three ways of doing that:

Using @JsonIgnore

You can try to add the @JsonIgnore only on your getter:

    @JsonIgnore
    private String password;

Or:

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

Using @JsonProperty access

You can add @JsonProperty annotation on your field:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;

WRITE_ONLY Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.

Using @JsonIgnoreProperties

Adding the properties you want to ignore on your class:

@JsonIgnoreProperties({"password"})
public class User {
    private String userName;
    private String password;
}

I usually go with @JsonIgnoreProperties when I want to extend some class and ignore some properties of the parent.

nortontgueno
  • 2,553
  • 1
  • 24
  • 36
  • it seems can not use like @jsonview that i can set some config to fit different situation – Ted.Xiong May 19 '19 at 15:30
  • Might [this](https://stackoverflow.com/questions/51172496/how-to-dynamically-ignore-a-property-on-jackson-serialization) can help you then – nortontgueno May 19 '19 at 15:37