使用Retrofit + GSON + SugarORM

时间:2016-01-18 11:19:16

标签: android json gson sugarorm retrofit2

我正在使用Retrofit和GSON根据this tutorial获取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:无法为其创建转换器   class 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)                                                                            at 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)                                                                            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)                                                                         引起:java.lang.IllegalArgumentException:无法创建   类uz.cp.retrofitsandbox.GitResult的转换器                                                                            方法GitApiInterface.getUsersNamedTom                                                                            at retrofit.Utils.methodError(Utils.java:201)                                                                            在   retrofit.MethodHandler.createResponseConverter(MethodHandler.java:67)                                                                            at retrofit.MethodHandler.create(MethodHandler.java:32)                                                                            at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)                                                                            at retrofit.Retrofit $ 1.invoke(Retrofit.java:127)                                                                            在java.lang.reflect.Proxy.invoke(Proxy.java:397)                                                                            在$ Proxy0.getUsersNamedTom(未知来源)                                                                            at 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声明了多个名为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)                                                                            at retrofit.GsonConverterFactory.get(GsonConverterFactory.java:50)                                                                            at retrofit.Utils.resolveConverter(Utils.java:72)                                                                            在   retrofit.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;
    }

}

1 个答案:

答案 0 :(得分:0)

在您的班级uz.cp.retrofitsandbox.Item中,您有多个具有JSON名称id的字段。确保映射是一对一的。