本文介绍了无法用List使用Gson反序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following exception while deserializing an JSON to object using Gson:

应该代表JSON的类是:

The class which should represent the JSON is:

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

奇怪的是,它可以在一些机器上运行,而不是在其他机器上运行。
任何想法?

The odd thing is that it works on some machines and not on others.Any idea?

推荐答案

我尝试过你的例子:

I tried your example with this:

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

它的工作原理(请注意,您的示例中的字符串没有转义引号) 。

and it worked (pay attention that your string in example has no escaped quotes).

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,并检查了源代码:库中没有该错误字符串。

So my best guess it that your team is working with different versions of the library. I'm using Gson 2.2.4 and I checked the source code: that error string is not present in the library.

这篇关于无法用List使用Gson反序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:21
查看更多