【问题标题】:Stack overflow exception when i use strategy for Gson当我对 Gson 使用策略时堆栈溢出异常
【发布时间】:2018-04-04 17:16:55
【问题描述】:

我正在尝试将对象作为 json 字符串保存到文件中!但是当我尝试在没有 GsonBuilder 的 ExclusionStrategy 的情况下这样做时,它给了我一个“我的班级中 Json 异常字段 hashCode_ 中的重复名称”!我在谷歌搜索并找到了一个我应该使用 ExclusionStrategy 并跳过一些字段的解决方案!所以我这样做了,这次我得到了堆栈溢出异常!我不知道该怎么办,互联网上似乎没有这个问题的答案!

这是我的 convertToJsonString 方法:

public static <E> String convertToJsonString(E e) {

    ExclusionStrategy strategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            if(f.getName().equals("hashCode_"))
                return true;

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
    gson=new GsonBuilder().setExclusionStrategies(strategy).create();
    return gson.toJson(e);
}

这是我制作 JsonElement 的地方

   public static <E> JsonElement createJsonElement(E e) {
      return gson.toJsonTree(e);
   }

这是我将 jsonString 保存到文件的地方:

   public void writeToFileHotel(Hotel hotel) {

   JsonElement element= JsonUtils.createJsonElement(hotel);
    JsonUtils.writeJsonToFile(element,allGiataHotels_File);
}

这是我没有排除策略的例外

  Exception in thread "main" java.lang.IllegalArgumentException: class 
  ir.viratech.tickbed.model.user.AgencyUser declares multiple JSON fields 
  named hashCode_

这是我对 ExclusionStrategy 的例外

  Exception in thread "main" java.lang.StackOverflowError

注意:在 JsonElement element= JsonUtils.createJsonElement(hotel) 行上发生 IllegalArgumentException 异常

【问题讨论】:

  • gson.fromJson(json,JsonElement.class);你为什么喜欢这个
  • 不正确吗?如果是正确的代码是什么? @jeevanswamy21
  • 把它改成 gson.toJsonTree(e) 但还是一样
  • 已经转换然后返回传递值 gson.fromJson(json)
  • @jeevanswamy21 是的,你说得对,我纠正了它,但仍然得到 IllegalArgumentException 声明多个名为 hashCode_ 的 JSON 字段!!!

标签: java json gson


【解决方案1】:

当您的对象存在循环依赖时会发生 Stackoverflow 错误。

您可能需要使用 TypeAdapter

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 2010-11-27
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2016-02-19
    • 2012-05-28
    相关资源
    最近更新 更多