0

I am trying to create an entity like this

@Entity
public class Person extends Model {

  @Id
  public int id;

  public String name;

}

However when I do toJson(person), my result contains both the fields id and name. But I don't want the id 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 id field??

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

Yasser Hussain
  • 854
  • 7
  • 21
  • This could be marked as a duplicate of http://stackoverflow.com/questions/30440902/java-object-to-json-with-only-selected-fields – Yasser Hussain Jul 20 '16 at 08:51

3 Answers3

1

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.

@JsonIgnore
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

Community
  • 1
  • 1
Ave
  • 4,338
  • 4
  • 40
  • 67
  • yeah gson uses transient. I was asking about play's `toJson` method. Adding transient to `id` field did not help. Ids still come up in my json with '0' as values. – Yasser Hussain Jul 20 '16 at 08:21
  • So, you should read this question: http://stackoverflow.com/questions/30440902/java-object-to-json-with-only-selected-fields This will resolve your question. – Ave Jul 20 '16 at 08:26
  • Your previous comment is the correct answer but not your post. Would you care to elaborate your comment above and post it so that I can mark it correct?. – Yasser Hussain Jul 20 '16 at 08:50
  • If you see my answer is helpful. Please accept this to other user can see. I updated my answer. – Ave Jul 20 '16 at 09:09
0

AFAIK Play! uses Gson which doesn´t serialize transient fields.

So I think adding transient modifier like this:

@Id
public transient int id;

should do it.

PrimosK
  • 13,848
  • 10
  • 60
  • 78
0

In gson,the most simple way is adding transient as

public transient int id;

or you can add annotation @Expose and

new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

to realize it

kevin
  • 1
  • 3