Gson POJO映射丢失自定义字段值 [英] Gson POJO mapping loses custom field value

查看:263
本文介绍了Gson POJO映射丢失自定义字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Gson将JSON映射到POJO,其中POJO包含不属于JSON的自定义字段。当其他字段的设置者被调用以将正在更新的字段的名称添加到列表时,该字段被更新。



POJO类看起来像这样:

  public class myPojo {

private List< String> dirtyFields;
私人字符串ID;
private String subject;
私有字符串标题;

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);
}

//更多setter / getters
}



dirtyFields ivar不是反序列化的字段,但它用于跟踪正在更新的字段。
然而,映射后,列表似乎变成了一个空的列表。 Jackson的情况并非如此。
这是由于预期的Gson行为吗?

解决方案

Gson在反序列化/序列化过程中不调用setter / getters。它使用反射直接访问字段(即使是私有/受保护的)。这就解释了为什么你的 dirtyFields ivar是空的。

据我所知,Gson没有实现调用setter / getters的可能性。 Gson这样做的原因在此处更好解释。杰克逊和Gson功能的比较可以在这里找到,您可能对setter / getter部分感兴趣。



然而Gson非常灵活地添加自定义行为来获取所需内容,您应该开始阅读使用方法(即getters& setters)bug读取和写入Json属性



另一种计算 dirtyFields 列表可以使用反射并检查POJO的每个字段是否为空。您可以从开始。


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?

解决方案

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.

这篇关于Gson POJO映射丢失自定义字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆