2

I'm trying to use Gson to map JSON to POJO where the POJO contains a custom field that is not part of JSON. The field gets updated when the setters of other fields are invoked to add the names of the fields that are being updated to a list.

The POJO class looks something like this:

public class myPojo {

  private List<String> dirtyFields;
  private String id;
  private String subject;
  private String title;

  public myPojo() {
     dirtyFields = new ArrayList<String>();
  }

  public getId() {
     return id;
  }

  public setId(String id) {
    this.id = id;
  }

  public getSubject() {
    return subject;
  }

 public setSubject(String subject) {
    this.subject = subject;
    dirtyFields.add("subject");
 }

 // more setter/getters
}

The dirtyFields ivar is not a deserialized field but it is used to keep track of the fields that are being updated. After mapping, however, the list seems to become an empty list. This was not the case with Jackson. Is this due to the expected Gson behaviour?

giampaolo
  • 6,906
  • 5
  • 45
  • 73

1 Answers1

1

Gson does not call setter/getters during deserialization/serialization. It access, instead, directly to fields (even if private/protected) using reflection. This explains why your dirtyFields ivar is empty.

The possibility of calling setter/getters is not implemented in Gson as far as I know. The reason why Gson acts like this is explained better here. A comparison between Jackson and Gson features can be found here, you may be interested in setter/getter part.

However Gson is quite flexible to add a custom behavior to get what you need, you should start reading Read and write Json properties using methods (ie. getters & setters) bug

Another way to calculate your dirtyFields list could be using reflection and checking if every field of your POJO is null or not. You could start from this.

Community
  • 1
  • 1
giampaolo
  • 6,906
  • 5
  • 45
  • 73
  • Thanks for the information. The problem with checking for null is that the actual models contain primitives such as long. – user2847684 Oct 08 '13 at 13:39
  • I got it. But if you use Java > 1.5 you could use Long instead of long and check Long field was filled by Gson. – giampaolo Oct 09 '13 at 17:41