根据本教程,我正在使用 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: 无法启动活动 ComponentInfo{uz. cp.retrofitsandbox/uz.cp.retrofitsandbox.MainActivity}:java.lang.IllegalArgumentException:无法在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(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit. java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 原因:java.lang.IllegalArgumentException:无法为方法 GitApiInterface 的 uz.cp.retrofitsandbox.GitResult 类创建转换器。getUsersNamedTom 在 retrofit.Utils.methodError(Utils.java:201) 在 retrofit.MethodHandler.createResponseConverter(MethodHandler.java:67) 在 retrofit.MethodHandler.create(MethodHandler.java:32) 在 retrofit.Retrofit.loadMethodHandler(Retrofit.java :138) 在 retrofit.Retrofit$1.invoke(Retrofit.java:127) 在 java.lang.reflect.Proxy.invoke(Proxy.java:397) 在 $Proxy0.getUsersNamedTom(Unknown Source) 在 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: class uz.cp.retrofitsandbox.Item 在 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:146) 在 com.google 声明多个名为 id 的 JSON 字段.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) at com.google.gson.Gson.getAdapter(Gson.java:359) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122) at 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) 在 retrofit.GsonConverterFactory.get(GsonConverterFactory.java:50) 在 retrofit.Utils.resolveConverter(Utils.java:72) 在改造.MethodHandler.createResponseConverter(MethodHandler.java:65) ... 19 更多
此错误将我引导至此行(27):
Call<GitResult> call = service.getUsersNamedTom("tom");
所以我的问题是:为什么会发生这个错误?如何解决这个问题?
构建.gradle(应用程序)
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;
}
}
项目.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;
}
}