Yasser Hussain Yasser Hussain - 3 months ago 8x
Java Question

How to make toJson in Play skip some fields in the model without using external libraries?

I am trying to create an entity like this

public class Person extends Model {

public int id;

public String name;


However when I do toJson(person), my result contains both the fields
. But I don't want the
to be shown.

Is there any annotation or something (like gson's Expose, for example) which will make toJson skip some fields so that the final json output does not contain the

[Short Answer] - Use @JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)


You have two options:

First, In case you need to skip some fields without using external libraries: You can see original question and answer at:

Java object to JSON with only selected fields

You can use the @JsonIgnore annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.

public String name;

Second, other method is quickly from @ChrisSeline if you using Gson library:

Any fields you don't want to be serialized in general you should use the "transient" modifier, and this also applies to JSON serializers (at least it does to a few that I have used, including Gson).

If you don't want name to show up in the serialised JSON give it a transient keyword, e.g.,

private transient String name;

Details Here