【问题标题】:Failed to deserialize an object with List using Gson无法使用 Gson 反序列化带有 List 的对象
【发布时间】:2013-09-16 08:37:51
【问题描述】:

使用 Gson 将 JSON 反序列化为对象时出现以下异常:

com.google.gson.JsonParseException:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@588722d6 未能反序列化 json 对象 [{"time":1378911600000,"total":0},{"time":1378912500000 ,"total":0},{"time":1378913400000,"total":2,"sum":130000,"avgLen":65000.0}] 给定类型 com.google.gson.ParameterizedTypeImpl@490ca2fa

应该代表 JSON 的类是:

public class Api{

   private List<ApiData> avgEngLength;

   public Api() {
   }
}

public class ApiData{

private Long time;
private Long total;
private Long sum;
private Double avgLen;

public ApiData(Long time, Long total, Long sum, Double avgLen) {
    this.time = time;
    this.total= total;
    this.sum= sum;
    this.avgLen= avgLen;
 }
}

反序列化的代码是:

 String json = "{\"avgEngLength\":[{\"time\":1378905300000,\"total\":0},{\"time\":1378906200000,\"total\":2,\"sum\":130000,\"avgLen\":65000.0}]}";
 Gson gson = new GsonBuilder().create();
 return gson.fromJson(json, Api.class);

奇怪的是它可以在某些机器上运行,而在其他机器上却不行。 有什么想法吗?

【问题讨论】:

  • 您使用的是什么版本的 Gson?您是否向您的构建器提供了一些未在示例中报告的自定义行为?

标签: java json gson


【解决方案1】:

我用这个试过你的例子:

public static void main(String[] args) {

    String s = "{\"avgEngLength\":[{\"time\":1378905300000,\"total\":0},{\"time\":1378906200000,\"total\":2,\"sum\":130000,\"avgLen\":65000.0}]}";

    Gson gson = new GsonBuilder().create();
    Api a = gson.fromJson(s, Api.class);
    System.out.println(a);
    }

并且它起作用了(注意示例中的字符串没有转义引号)。

Api [avgEngLength=[ApiData [time=1378905300000, total=0, sum=null, avgLen=null], ApiData [time=1378906200000, total=2, sum=130000, avgLen=65000.0]]]

所以我猜你的团队正在使用不同版本的库。我正在使用 Gson 2.2.4 并检查了源代码:库中不存在该错误字符串。

【讨论】:

  • 正如我所说,它在某些机器上工作(我认为只在 Windows 上)而不是在其他机器上
  • 您有时间检查引发异常的计算机上的库版本吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多