【发布时间】:2016-04-23 13:11:14
【问题描述】:
根据this tutorial,我正在使用 Retrofit 和 GSON 获取 JSON 并将其序列化为 POJO。一切正常。为了将实例保存到 SQLite 数据库中,我使用了 Sugar ORM。我的 POJO 有字段 - 整数 ID。
@Generated("org.jsonschema2pojo")
public class Item extends SugarRecord{
@SerializedName("login")
@Expose
private String login;
@SerializedName("id")
@Expose
private Long id;
Sugar ORM 要求 Integer id 应该是 Long。我说好的,把它弄长了。当我运行我的应用程序时,会出现此错误:
01-18 06:03:44.436 4498-4498/uz.cp.retrofitsandbox E/AndroidRuntime: 致命例外:主要 进程:uz.cp.retrofitsandbox,PID:4498 java.lang.RuntimeException:无法启动活动 组件信息{uz.cp.retrofitsandbox/uz.cp.retrofitsandbox.MainActivity}: java.lang.IllegalArgumentException:无法创建转换器 uz.cp.retrofitsandbox.GitResult 类 对于方法 GitApiInterface.getUsersNamedTom 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在 android.app.ActivityThread.access$800(ActivityThread.java:144) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5221) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 引起:java.lang.IllegalArgumentException:无法创建 uz.cp.retrofitsandbox.GitResult 类的转换器 对于方法 GitApiInterface.getUsersNamedTom 在改造.Utils.methodError(Utils.java:201) 在 改造.MethodHandler.createResponseConverter(MethodHandler.java:67) 在改造.MethodHandler.create(MethodHandler.java:32) 在改造.Retrofit.loadMethodHandler(Retrofit.java:138) 在改造.Retrofit$1.invoke(Retrofit.java:127) 在 java.lang.reflect.Proxy.invoke(Proxy.java:397) 在 $Proxy0.getUsersNamedTom(未知来源) 在 uz.cp.retrofitsandbox.MainActivity.onCreate(MainActivity.java:27) 在 android.app.Activity.performCreate(Activity.java:5933) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) ... 10 更多 引起:java.lang.IllegalArgumentException:类 uz.cp.retrofitsandbox.Item 声明多个名为 id 的 JSON 字段 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:146) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83) 在 com.google.gson.Gson.getAdapter(Gson.java:359) 在 com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52) 在 com.google.gson.Gson.getAdapter(Gson.java:359) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.(ReflectiveTypeAdapterFactory.java:92) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142) 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83) 在 com.google.gson.Gson.getAdapter(Gson.java:359) 在改造.GsonConverterFactory.get(GsonConverterFactory.java:50) 在改造.Utils.resolveConverter(Utils.java:72) 在 改造.MethodHandler.createResponseConverter(MethodHandler.java:65) ... 19 更多
这个错误将我引导到这一行(27):
Call<GitResult> call = service.getUsersNamedTom("tom");
所以我的问题是:为什么会发生这个错误?如何解决这个问题?
build.gradle(app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "uz.cp.retrofitsandbox"
minSdkVersion 9
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'org.glassfish.main:javax.annotation:4.0-b33'
compile 'com.github.satyan:sugar:1.4'
}
onCreate(MainActivity.java):
String baseUrl = "https://api.github.com" ;
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
GitApiInterface service = client.create(GitApiInterface.class);
Call<GitResult> call = service.getUsersNamedTom("tom");
call.enqueue(new Callback<GitResult>() {
@Override
public void onResponse(Response<GitResult> response) {
if (response.isSuccess()) {
GitResult result = response.body();
result.save();
GitResult gitResult = GitResult.first(GitResult.class);
Toast.makeText(getApplicationContext(), String.valueOf(gitResult.getItems().size()), Toast.LENGTH_LONG).show();
} else {
//request not successful (like 400,401,403 etc)
//Handle errors
}
}
@Override
public void onFailure(Throwable t) {
}
});
GitApiInterface.java
package uz.cp.retrofitsandbox;
import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
/**
* Created by Joe on 1/18/2016.
*/
public interface GitApiInterface {
@GET("/search/users")
Call<GitResult> getUsersNamedTom(@Query("q") String name);
@POST("/user/create")
Call<Item> createUser(@Body String name, @Body String email);
@PUT("/user/{id}/update")
Call<Item> updateUser(@Path("id") String id , @Body Item user);
}
GitResult.java
package uz.cp.retrofitsandbox;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.orm.SugarRecord;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class GitResult extends SugarRecord{
@SerializedName("total_count")
@Expose
private Integer totalCount;
@SerializedName("incomplete_results")
@Expose
private Boolean incompleteResults;
@SerializedName("items")
@Expose
private List<Item> items = new ArrayList<Item>();
/**
* No args constructor for use in serialization
*
*/
public GitResult() {
}
/**
*
* @param items
* @param totalCount
* @param incompleteResults
*/
public GitResult(Integer totalCount, Boolean incompleteResults, List<Item> items) {
this.totalCount = totalCount;
this.incompleteResults = incompleteResults;
this.items = items;
}
/**
*
* @return
* The totalCount
*/
public Integer getTotalCount() {
return totalCount;
}
/**
*
* @param totalCount
* The total_count
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
/**
*
* @return
* The incompleteResults
*/
public Boolean getIncompleteResults() {
return incompleteResults;
}
/**
*
* @param incompleteResults
* The incomplete_results
*/
public void setIncompleteResults(Boolean incompleteResults) {
this.incompleteResults = incompleteResults;
}
/**
*
* @return
* The items
*/
public List<Item> getItems() {
return items;
}
/**
*
* @param items
* The items
*/
public void setItems(List<Item> items) {
this.items = items;
}
}
Item.java
package uz.cp.retrofitsandbox;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.orm.SugarRecord;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class Item extends SugarRecord{
@SerializedName("login")
@Expose
private String login;
@SerializedName("id")
@Expose
private Long id;
@SerializedName("avatar_url")
@Expose
private String avatarUrl;
@SerializedName("gravatar_id")
@Expose
private String gravatarId;
@SerializedName("url")
@Expose
private String url;
@SerializedName("html_url")
@Expose
private String htmlUrl;
@SerializedName("followers_url")
@Expose
private String followersUrl;
@SerializedName("following_url")
@Expose
private String followingUrl;
@SerializedName("gists_url")
@Expose
private String gistsUrl;
@SerializedName("starred_url")
@Expose
private String starredUrl;
@SerializedName("subscriptions_url")
@Expose
private String subscriptionsUrl;
@SerializedName("organizations_url")
@Expose
private String organizationsUrl;
@SerializedName("repos_url")
@Expose
private String reposUrl;
@SerializedName("events_url")
@Expose
private String eventsUrl;
@SerializedName("received_events_url")
@Expose
private String receivedEventsUrl;
@SerializedName("type")
@Expose
private String type;
@SerializedName("site_admin")
@Expose
private Boolean siteAdmin;
@SerializedName("score")
@Expose
private Double score;
/**
* No args constructor for use in serialization
*
*/
public Item() {
}
/**
*
* @param eventsUrl
* @param siteAdmin
* @param gistsUrl
* @param score
* @param type
* @param gravatarId
* @param url
* @param subscriptionsUrl
* @param id
* @param followersUrl
* @param reposUrl
* @param htmlUrl
* @param receivedEventsUrl
* @param avatarUrl
* @param followingUrl
* @param login
* @param organizationsUrl
* @param starredUrl
*/
public Item(String login, Long id, String avatarUrl, String gravatarId, String url, String htmlUrl, String followersUrl, String followingUrl, String gistsUrl, String starredUrl, String subscriptionsUrl, String organizationsUrl, String reposUrl, String eventsUrl, String receivedEventsUrl, String type, Boolean siteAdmin, Double score) {
this.login = login;
this.id = id;
this.avatarUrl = avatarUrl;
this.gravatarId = gravatarId;
this.url = url;
this.htmlUrl = htmlUrl;
this.followersUrl = followersUrl;
this.followingUrl = followingUrl;
this.gistsUrl = gistsUrl;
this.starredUrl = starredUrl;
this.subscriptionsUrl = subscriptionsUrl;
this.organizationsUrl = organizationsUrl;
this.reposUrl = reposUrl;
this.eventsUrl = eventsUrl;
this.receivedEventsUrl = receivedEventsUrl;
this.type = type;
this.siteAdmin = siteAdmin;
this.score = score;
}
/**
*
* @return
* The login
*/
public String getLogin() {
return login;
}
/**
*
* @param login
* The login
*/
public void setLogin(String login) {
this.login = login;
}
/**
*
* @return
* The id
*/
public Long getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Long id) {
this.id = id;
}
/**
*
* @return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* @param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
/**
*
* @return
* The gravatarId
*/
public String getGravatarId() {
return gravatarId;
}
/**
*
* @param gravatarId
* The gravatar_id
*/
public void setGravatarId(String gravatarId) {
this.gravatarId = gravatarId;
}
/**
*
* @return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* @return
* The htmlUrl
*/
public String getHtmlUrl() {
return htmlUrl;
}
/**
*
* @param htmlUrl
* The html_url
*/
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
/**
*
* @return
* The followersUrl
*/
public String getFollowersUrl() {
return followersUrl;
}
/**
*
* @param followersUrl
* The followers_url
*/
public void setFollowersUrl(String followersUrl) {
this.followersUrl = followersUrl;
}
/**
*
* @return
* The followingUrl
*/
public String getFollowingUrl() {
return followingUrl;
}
/**
*
* @param followingUrl
* The following_url
*/
public void setFollowingUrl(String followingUrl) {
this.followingUrl = followingUrl;
}
/**
*
* @return
* The gistsUrl
*/
public String getGistsUrl() {
return gistsUrl;
}
/**
*
* @param gistsUrl
* The gists_url
*/
public void setGistsUrl(String gistsUrl) {
this.gistsUrl = gistsUrl;
}
/**
*
* @return
* The starredUrl
*/
public String getStarredUrl() {
return starredUrl;
}
/**
*
* @param starredUrl
* The starred_url
*/
public void setStarredUrl(String starredUrl) {
this.starredUrl = starredUrl;
}
/**
*
* @return
* The subscriptionsUrl
*/
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
/**
*
* @param subscriptionsUrl
* The subscriptions_url
*/
public void setSubscriptionsUrl(String subscriptionsUrl) {
this.subscriptionsUrl = subscriptionsUrl;
}
/**
*
* @return
* The organizationsUrl
*/
public String getOrganizationsUrl() {
return organizationsUrl;
}
/**
*
* @param organizationsUrl
* The organizations_url
*/
public void setOrganizationsUrl(String organizationsUrl) {
this.organizationsUrl = organizationsUrl;
}
/**
*
* @return
* The reposUrl
*/
public String getReposUrl() {
return reposUrl;
}
/**
*
* @param reposUrl
* The repos_url
*/
public void setReposUrl(String reposUrl) {
this.reposUrl = reposUrl;
}
/**
*
* @return
* The eventsUrl
*/
public String getEventsUrl() {
return eventsUrl;
}
/**
*
* @param eventsUrl
* The events_url
*/
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
/**
*
* @return
* The receivedEventsUrl
*/
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
/**
*
* @param receivedEventsUrl
* The received_events_url
*/
public void setReceivedEventsUrl(String receivedEventsUrl) {
this.receivedEventsUrl = receivedEventsUrl;
}
/**
*
* @return
* The type
*/
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The siteAdmin
*/
public Boolean getSiteAdmin() {
return siteAdmin;
}
/**
*
* @param siteAdmin
* The site_admin
*/
public void setSiteAdmin(Boolean siteAdmin) {
this.siteAdmin = siteAdmin;
}
/**
*
* @return
* The score
*/
public Double getScore() {
return score;
}
/**
*
* @param score
* The score
*/
public void setScore(Double score) {
this.score = score;
}
}
【问题讨论】:
-
你能把你正在初始化改造的 build.gradle 和 sn-p 贴出来吗?
-
@Blackbelt,我添加了 build.gradle 并在其中初始化了 Retrofit。如果需要,我可以发布 GitResult 和项目代码。
-
你能发
GitResult和GitApiInterface吗? -
@Blackbelt,我添加了 GitApiInterface、GitResult 和 Item 类
-
你可以尝试在不创建
GitResultextends SugarRecord{的情况下运行它
标签: android json gson sugarorm retrofit2