Gson POJO mapping loses custom field value

痴心易碎 提交于 2019-12-13 18:38:50

问题


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?


回答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.



来源:https://stackoverflow.com/questions/19188437/gson-pojo-mapping-loses-custom-field-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!