简体   繁体   English

Gson POJO映射丢失了自定义字段值

[英]Gson POJO mapping loses custom field value

I'm trying to use Gson to map JSON to POJO where the POJO contains a custom field that is not part of JSON. 我正在尝试使用Gson将JSON映射到POJO,其中POJO包含不属于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: POJO类看起来像这样:

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. dirtyFields ivar不是反序列化的字段,但用于跟踪正在更新的字段。 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? 这是由于预期的Gson行为吗?

Gson does not call setter/getters during deserialization/serialization. 在反序列化/序列化期间,Gson不会调用setter / getter。 It access, instead, directly to fields (even if private/protected) using reflection. 相反,它使用反射直接访问字段(即使是私有/受保护的)。 This explains why your dirtyFields ivar is empty. 这解释了为什么您的dirtyFields ivar为空。

The possibility of calling setter/getters is not implemented in Gson as far as I know. 据我所知,在Gson中没有实现调用setter / getter的可能性。 The reason why Gson acts like this is explained better here . Gson之所以如此行事的原因在这里得到了更好的解释。 A comparison between Jackson and Gson features can be found here , you may be interested in setter/getter part. 可以在此处找到Jackson和Gson功能之间的比较,您可能会对setter / getter部分感兴趣。

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 但是,Gson非常灵活地添加自定义行为来获得所需的内容,您应该开始阅读使用方法(即getter和setter)bug读取和写入Json属性。

Another way to calculate your dirtyFields list could be using reflection and checking if every field of your POJO is null or not. 计算dirtyFields列表的另一种方法是使用反射并检查POJO的每个字段是否为空。 You could start from this . 您可以从这里开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM