【发布时间】:2014-02-23 14:54:22
【问题描述】:
我正在尝试将一些 JSON 转换为 android 中的 java 对象,但它似乎不起作用。
Gson gson = new Gson();
Person person = gson.fromJson(s, Person.class);
Toast toast = Toast.makeText(getApplicationContext(), "Welcome back " + person.getDisplayName(), duration);
toast.show();
Person.class 在哪里
com.google.api.services.plus.model.Person
我收到类型转换错误,例如:
wrong object type: Ljava/lang/Double; Ljava/lang/Integer;
java.lang.IllegalArgumentException: invalid value for field
但我想重用 API 库中的这个模型对象,有没有办法解决这个问题?
编辑:
为了以更简单的形式证明这个问题,请参考这个例子。
com.google.api.services.plus.model.Person;
Gson g = new Gson();
Person p1 = new Person();
p1.setDisplayName("Test");
p1.setCircledByCount(10);
String json = g.toJson(p1);
Person fromJson = g.fromJson(json, Person.class);
System.out.println(fromJson.getDisplayName());
抛出同样的异常。
Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.google.api.services.plus.model.Person.circledByCount to java.lang.Double
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
我做错了吗? 谢谢
【问题讨论】:
-
发布你的模型类和json
-
老实说,您不应该在该类中使用 GSON。它不是为与 GSON 一起使用而设计的。它有自己的内置逻辑,用于将自身序列化为 JSON,并且它所属的库处理对它的反序列化。
标签: java android json google-api gson