Gson试图解析用@Expose(false)注释的字段并崩溃

Raf*_*ima 8 android json gson

我正在尝试使用Gson将一个非常基本的对象序列化为JSON.

这是班级

@org.greenrobot.greendao.annotation.Entity
public class Giveaway {

    @Id(autoincrement = true)
    @Expose(serialize = false,deserialize = false)
    private Long id;

    @NotNull
    private String owner;

    private Date raffleDate;
    private String thumbnailUrl;

    @ToMany(referencedJoinProperty = "giveawayId")
    private List<Influencer> mustFollowList;


    @NotNull
    @Convert(converter = GiveawayCommentTypeConverter.class, columnType = Integer.class)
    private GiveawayCommentType tipo;


    private String specifWordValue;
    private Integer amountFriendsToIndicate;

    @NotNull
    @Unique
    private String mediaId;


    //to reflect the relationships
    @ToMany(referencedJoinProperty = "raffle")
    @Expose(deserialize = false, serialize = false)
    private List<UserOnGiveaway> attendantsTickets;
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我有2个字段,我不想被序列化,所以我用它注释expose = false,但即使有这个Gson正在尝试序列化它们并崩溃到期OutOfMemory.(UserOnGiveaway与Giveaway有一个循环引用,这解释了它崩溃的原因.)

Gson代码是:

        Gson parser = new GsonBuilder().setPrettyPrinting().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();
        StringBuilder sb = new StringBuilder(200);
        try {
            for (Giveaway g : this.dao.getGiveawayDao().loadAll())
                sb.append(parser.toJson(g) + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

我不想使用,.excludeFieldsWithoutExposeAnnotation()因为它迫使我写出超出必要的方式并且为了排除1个字段而禁止一切...

我究竟做错了什么?

Dmi*_*try 1

在您的字段中使用transientJava 关键字attendantsTickets,但不要用于@Expose您的案例。

来自文档https://github.com/google/gson/blob/master/UserGuide.md:“如果一个字段被标记为瞬态,(默认情况下)它将被忽略并且不包含在 JSON 序列化或反序列化中。”

private transient List<UserOnGiveaway> attendantsTickets;
Run Code Online (Sandbox Code Playgroud)

另请查看此 Gson 配置选项:GsonBuilder.excludeFieldsWithModifiers(int... modifiers)

transient有关java的更多信息,您可以在这里阅读https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.3


如果您的代码依赖于瞬态行为,例如 JPA 或其他数据映射工具,您将不得不使用 Gson 排除策略。

您可以创建注释并用它标记应受自定义序列化影响的字段,如下所示,然后在排除策略代码中使用它:

    @Target(value = ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface ExcludeFromJson {
    }

.........

    void gson() {

        new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
          @Override
          boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(ExcludeFromJson.class) != null;
          }

          @Override
          boolean shouldSkipClass(Class<?> clazz) {
            return false;
          }
        })
      }

..........

@ExcludeFromJson
private transient List<UserOnGiveaway> attendantsTickets;
Run Code Online (Sandbox Code Playgroud)