Thadeu Melo
Thadeu Melo

Reputation: 991

@JsonIgnore does not ignore fields in hibernate Entity

I have an Entity "Task" that has an Id property, but I don't need the field to be returned in the JSON file.

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer Id;
    @JsonProperty("task")
    private String taskName;

    private String status;
    //getter and setter
}

However, the annotation @JsonIgnore doesn't filter the field when I make the get request, see below:

{
    "status": "started",
    "timestamps": {
        "submitted": "2018-12-31T00:34:20.718+0000",
        "started": "2018-12-31T00:34:20.718+0000",
        "completed": "2018-12-31T00:34:20.718+0000"
    },
    "id": 40001,
    "task": "q094hiu3o"
}

What is the proper way to prevent "Id" to be displayed?

Upvotes: 4

Views: 7371

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

So here is the problem jackson had issue with hibernate issue, try using @jsonIgnoreProperties on class level

@JsonIgnoreProperties(ignoreUnknown = true, 
                  value = {"id"})

Upvotes: 5

nortontgueno
nortontgueno

Reputation: 2801

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

    @JsonIgnore
    public Integer getId() {
        return id;
    }

Also I would suggest to add the @JsonProperty annotation on your id field, if it is available in the Jackson version you are using:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty(access = Access.WRITE_ONLY)
private Integer id;

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.

Jackson documentation here

Upvotes: 2

Related Questions