16

I want to hide the "id" item in the model, how to do this in java?

Vladas Maier
  • 2,054
  • 2
  • 22
  • 34
Vision Yang
  • 175
  • 1
  • 1
  • 8
  • did you try @JsonIgnore? – dharam Nov 12 '18 at 13:23
  • Possible duplicate of [Ignoring JSON fields when sending an object (deserialization)](https://stackoverflow.com/questions/50532345/ignoring-json-fields-when-sending-an-object-deserialization) and [How to ignore swagger resource property for specific HTTP verb (GET,POST,PUT)](https://stackoverflow.com/q/42359204/113116) – Helen Nov 12 '18 at 13:33
  • @dharam I want to partically hide, not all method hide the "id". – Vision Yang Nov 12 '18 at 13:44
  • sorry! my method will do it for all references... need to do some custom code to get rid of it for just one flow – dharam Nov 12 '18 at 13:46
  • @dharam yeah. For example, I have GET and POST, I want the "id" shows in the GET, but not POST, so I don't know how to do this. – Vision Yang Nov 12 '18 at 13:51
  • BTW, POST must return a 201 status and the id of the resources in a pure ReSTful service.. In your case, the solution is custom - You can have a look here https://www.baeldung.com/jackson-serialize-field-custom-criteria . You might also write a CustomJsonIgnore annotation which takes an argument (method/criteria) to serialize the field. Best of luck – dharam Nov 12 '18 at 13:55
  • Try `@ApiModelProperty(readOnly = true)` as explained [here](https://stackoverflow.com/a/50533209/113116). – Helen Nov 12 '18 at 14:31
  • probable duplicate of https://stackoverflow.com/questions/27777537/exclude-models-or-properties-from-swagger-response/58728653?noredirect=1#comment103749587_58728653 – suraj.tripathi Nov 06 '19 at 17:33
  • I am not getting this annotation `@ApiModelProperty` when I used `openapi-ui`. What could be the annotation for this? – Shailendra Madda Jul 10 '20 at 06:21
  • I don't think you can do it using the same DTO in the GET and POST. I am looking for the same because and the only way to do what you are saying is using diferent DTO to each method. – noNihongo Aug 31 '20 at 12:35

5 Answers5

13

to hide a request field in Swagger API v2:

 @ApiModelProperty(hidden = true) 
 private String id;

in OpenAPI v3:

@Schema(accessMode = Schema.AccessMode.READ_ONLY)
private String id;
user11153
  • 8,536
  • 5
  • 47
  • 50
Younes Ouchala
  • 300
  • 1
  • 4
  • 15
8
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@ApiModelProperty(accessMode = ApiModelProperty.AccessMode.READ_ONLY)
private String id;

Also see: https://github.com/springfox/springfox/issues/2816

LeonardoPF
  • 23
  • 7
Guru
  • 81
  • 1
  • 2
2

You can use @Hidden with Swagger Core 2.X

@Hidden -- Hides a resource, an operation or a property

Example from above link : Marks a given resource, class or bean type as hidden, skipping while reading / resolving.

@Path("/user")
@Produces({"application/json", "application/xml"})
public class HiddenAnnotatedUserResourceMethodAndData {
    UserData userData = new UserData();

    @POST
    @Hidden
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/1")
    public Response createUser(
            @Parameter(description = "Created user object", required = true) User user) {
        userData.addUser(user);
        return Response.ok().entity("").build();
    }

    @POST
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/2")
    public Response createUserWithHiddenBeanProperty(
            @Parameter(description = "Created user object", required = true) UserResourceBean user) {
        return Response.ok().entity("").build();
    }
}

Output of above

openapi: 3.0.1
paths:
  /user/2:
    post:
      summary: Create user
      description: This can only be done by the logged in user.
      operationId: createUserWithHiddenBeanProperty
      requestBody:
        description: Created user object
        content:
          '*/*':
            schema:
              $ref: '#/components/schemas/UserResourceBean'
        required: true
      responses:
        default:
          description: default response
components:
  schemas:
    UserResourceBean:
      type: object
      properties:
        foo:
          type: string
suraj.tripathi
  • 417
  • 2
  • 15
  • I now it is a bit old, but that answer doesn't fill the quastion because you are hidding the `resource (controller)`, What he really need is to hide only the filder `id`. – noNihongo Aug 31 '20 at 12:34
1

✍ Extends yours Entity & Use @JsonIgnoreProperties

public class UserVo {

@JsonIgnoreProperties("password")
public static class Public extends User {}

@JsonIgnoreProperties("userId")
public static class Save extends User {}

@JsonIgnoreProperties("password")
public static class Update extends User {}

}

✍ Entity Class ::

public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;

//  Write only access to password default in entity
// in order to hide it for update case we will extends class behaviour 
// in our custom views

// Instead of JsonViews i use custom views (i.e UserVo) with JsonProperty
// @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 


@NotBlank
@Schema(example = "lorem1234")
@Column(name = "password")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 
private String password; 

.....
}

✍ Controller Class ::

// See UserVo.Save in request body it serialize this class

@PostMapping(value = "/create")
public ResponseModel<User> createUser(@Valid @RequestBody UserVo.Save user) {
 // ... My dirty code comes here 
}

✍ Result ::

  • Easy Serialization;
  • No separate Domain classes
  • Easy Swagger Schema Hide ( Swagger knows hide Id on Add Operation )
Mohsin Ejaz
  • 316
  • 3
  • 7
0

Generally using DTO can be useful in this situation, for each entity, define one DTO(it depends on your project but most of the time can be useful) and then map your entity to DTO and vice versa with Mapstruct,after that in your DTO class by using @JsonIgnorProperties annotation on each field you want, you can omit that field from exposing by API services.

amir-rad
  • 85
  • 7