Java 在 Android 中使用 Retrofit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26500036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:39:03  来源:igfitidea点击:

Using Retrofit in Android

javaandroidapiretrofit

提问by Stack Man

I have an android app that has 3 activities :

我有一个有 3 个活动的 android 应用程序:

  1. A login activity
  2. A tasks acivity where all tasks pertaining to a user are displayed (Populated using an Array Adapter)
  3. A task_details activity which results from clicking a task on the list
  1. 登录活动
  2. 显示与用户有关的所有任务的任务活动(使用阵列适配器填充)
  3. 通过单击列表上的任务产生的 task_details 活动

I have to consume REST Apis. The research I have done so far directs me to use Retrofit. I checked how to use it and found out that :

我必须使用 REST API。到目前为止,我所做的研究指导我使用 Retrofit。我检查了如何使用它并发现:

  1. Set the base URL in the Main Activity (Mine is the Login Activity)
  2. I need to create a API class and define my functions using annotations.
  3. Use the class Rest Adapter in the Activity and define Callbacks.
  1. 在主活动中设置基本 URL(我的是登录活动)
  2. 我需要创建一个 API 类并使用注释定义我的函数。
  3. 在 Activity 中使用类 Rest Adapter 并定义回调。

Had my app been a single activity app, I would have crunched everything in my MainActivity.java but I don't know how and where to put all the code from steps 1,2,3 for use in my 3 activities.Could you please help by telling how to use Retrofit in my app. Thanks a lot.

如果我的应用程序是单个活动应用程序,我会处理 MainActivity.java 中的所有内容,但我不知道如何以及将步骤 1、2、3 中的所有代码放置在我的 3 个活动中。请问您通过告诉如何在我的应用程序中使用 Retrofit 来提供帮助。非常感谢。

Specifically, I need network calls to : 1. Login the user 2. Get all the tasks of the user. And for both I would be using a given REST api.

具体来说,我需要网络调用: 1. 登录用户 2. 获取用户的所有任务。对于两者,我都会使用给定的 REST api。

*********************************************
          Calling Api USing Retrofit
*********************************************
**Dependancies** :-
      implementation 'com.android.support:recyclerview-v7:27.1.1'
        implementation 'com.squareup.picasso:picasso:2.5.2'
        implementation 'com.android.support:cardview-v7:27.1.1'
    enter code here
**Model**
use the Pozo class

**Api Call**
 -> getLogin()    // use the method



  //API call for Login
    private void getLogin()
    {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams();
        requestParams.put("email_id", edit_email.getText().toString());
        requestParams.put("password", edit_password.getText().toString());
        Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
        Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
        client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                ShowProgress();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Hideprogress();

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("", "Login RESPONSE-" + response);
                Login login = new Gson().fromJson(String.valueOf(response), Login.class);
                edit_email.setText("");
                edit_password.setText("");
                if (login.getStatus().equals("true")) {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
                    mdToast.show();
                    Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());

                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
                    hideKeyboard(SignInActivity.this);
                    Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                    mdToast.show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("", throwable.getMessage());
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
                        MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                mdToast.show();
            }
        });
    }

采纳答案by Artemis

Using Retrofit is quite simple and straightforward.

使用 Retrofit 非常简单明了。

First of all you need to add retrofit to your project, as example with Gradle build sytem.

首先,您需要为项目添加改造,例如 Gradle 构建系统。

compile 'com.squareup.retrofit:retrofit:1.7.1' |

another way you can download .jar and place it to your libs folder.

另一种方法是您可以下载 .jar 并将其放置到您的 libs 文件夹中。

Then you need to define interfaces that will be used by Retrofit to make API calls to your REST endpoints. For example for users:

然后您需要定义接口,Retrofit 将使用这些接口对您的 REST 端点进行 API 调用。例如对于用户:

public interface YourUsersApi {

   //You can use rx.java for sophisticated composition of requests 
   @GET("/users/{user}")
   public Observable<SomeUserModel> fetchUser(@Path("user") String user);

   //or you can just get your model if you use json api
   @GET("/users/{user}")
   public SomeUserModel fetchUser(@Path("user") String user);

   //or if there are some special cases you can process your response manually 
   @GET("/users/{user}")
   public Response fetchUser(@Path("user") String user);

}

Ok. Now you have defined your API interface an you can try to use it.

好的。现在您已经定义了 API 接口,您可以尝试使用它。

To start you need to create an instance of RestAdapterand set base url of your API back-end. It's also quite simple:

首先,您需要创建一个RestAdapter实例并设置 API 后端的基本 URL。这也很简单:

RestAdapter restAdapter = new RestAdapter.Builder()
   .setEndpoint("https://yourserveraddress.com")
    .build();

YourUsersApi yourUsersApi = restAdapter.create(YourUsersApi.class);

Here Retrofit will read your information from interface and under the hood it will create RestHandleraccording to meta-info your provided which actually will perform HTTP requests.

这里 Retrofit 将从界面读取您的信息,并在后台根据您提供的元信息创建RestHandler,它实际上将执行 HTTP 请求。

Then under the hood, once response is received, in case of json api your data will be transformed to your model using Gson library so you should be aware of that fact that limitations that are present in Gson are actually there in Retrofit.

然后在后台,一旦收到响应,在 json api 的情况下,您的数据将使用 Gson 库转换为您的模型,因此您应该意识到 Gson 中存在的限制实际上存在于 Retrofit 中的事实。

To extend/override process of serialisers/deserialisation your response data to your models you might want to provide your custom serialisers/deserialisers to retrofit.

要扩展/覆盖序列化器/反序列化您对模型的响应数据的过程,您可能需要提供自定义序列化器/反序列化器进行改造。

Here you need to implement Converter interface and implement 2 methods fromBody()and toBody().

这里需要实现 Converter 接口并实现fromBody()toBody()2个方法。

Here is example:

这是示例:

public class SomeCustomRetrofitConverter implements Converter {

    private GsonBuilder gb;

    public SomeCustomRetrofitConverter() {
        gb = new GsonBuilder();

        //register your cursom custom type serialisers/deserialisers if needed
        gb.registerTypeAdapter(SomeCutsomType.class, new SomeCutsomTypeDeserializer());
    }

    public static final String ENCODING = "UTF-8";

    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        String charset = "UTF-8";
        if (body.mimeType() != null) {
            charset = MimeUtil.parseCharset(body.mimeType());
        }
        InputStreamReader isr = null;
        try {
           isr = new InputStreamReader(body.in(), charset);
           Gson gson = gb.create();
           return gson.fromJson(isr, type);
        } catch (IOException e) {
            throw new ConversionException(e);
        } catch (JsonParseException e) {
            throw new ConversionException(e);
        } finally {
            if (isr != null) {
                   try {
                      isr.close();
                   } catch (IOException ignored) {
                }
            }
        }
    }

    @Override
    public TypedOutput toBody(Object object) {
        try {
            Gson gson = gb.create();
            return new JsonTypedOutput(gson.toJson(object).getBytes(ENCODING), ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
     }

    private static class JsonTypedOutput implements TypedOutput {
        private final byte[] jsonBytes;
        private final String mimeType;

        JsonTypedOutput(byte[] jsonBytes, String encode) {
            this.jsonBytes = jsonBytes;
            this.mimeType = "application/json; charset=" + encode;
        }

        @Override
        public String fileName() {
            return null;
        }

       @Override
       public String mimeType() {
           return mimeType;
       }

       @Override
       public long length() {
          return jsonBytes.length;
       }

       @Override
       public void writeTo(OutputStream out) throws IOException {
           out.write(jsonBytes);
       }
    }
 }

And now you need to enable your custom adapters, if it was needed by using setConverter()on building RestAdapter

现在您需要启用您的自定义适配器,如果需要通过在构建 RestAdapter 时使用setConverter()

Ok. Now you are aware how you can get your data from server to your Android application. But you need somehow mange your data and invoke REST call in right place. There I would suggest to use android Service or AsyncTask or loader or rx.java that would query your data on background thread in order to not block your UI.

好的。现在您知道如何将数据从服务器获取到您的 Android 应用程序。但是您需要以某种方式管理您的数据并在正确的位置调用 REST 调用。在那里,我建议使用 android Service 或 AsyncTask 或 loader 或 rx.java 来查询后台线程上的数据,以免阻塞您的 UI。

So now you can find the most appropriate place to call

所以现在你可以找到最合适的地方打电话

SomeUserModel yourUser = yourUsersApi.fetchUser("someUsers")

to fetch your remote data.

获取您的远程数据。

回答by GreyBeardedGeek

Found a small, but complete and concise example at https://github.com/square/retrofit/tree/master/samples

https://github.com/square/retrofit/tree/master/samples找到了一个小而完整且简洁的示例

回答by nPn

Take a look at this , excellent blog on using Retrofit in conjunction with Otto, both libraries are from Square.

看看这个关于将 Retrofit 与 Otto 结合使用的优秀博客,这两个库都来自 Square。

http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html

http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html

The basic idea is that you will hold a reference to a "repository" object in your Application class. This object will have methods that "subscribe" to rest api event requests. When one is received it will make the proper Retrofit call, and then "post" the response, which can then be "subscribed" to by another component (such as the activity that made the request).

基本思想是您将持有对 Application 类中“存储库”对象的引用。该对象将具有“订阅”休息 api 事件请求的方法。当收到一个时,它将进行适当的 Retrofit 调用,然后“发布”响应,然后可以由另一个组件(例如发出请求的活动)“订阅”。

Once you have this all setup properly, accessing data via your rest api becomes very easy. For example, making are request for data would look something like this :

一旦你正确设置了这一切,通过你的rest api访问数据变得非常容易。例如,对数据的请求看起来像这样:

    mBus.post(new GetMicropostsRequest(mUserId));

and consuming the data would look something like this:

使用数据看起来像这样:

@Subscribe
public void onGetUserProfileResponse(GetUserProfileResponse event) {
    mView.setUserIcon("http://www.gravatar.com/avatar/" + event.getGravatar_id());
    mView.setUserName(event.getName());

}

It takes a little bit of upfront effort, but in the end it becomes "trivial" to access anything you need from our backend via Rest.

这需要一点前期的努力,但最终通过 Rest 从我们的后端访问您需要的任何东西变得“微不足道”。

回答by Ben Pearson

Firstly, putting everything in MainActivity would be bad practice and you would end up with a God object.

首先,把所有东西都放在 MainActivity 中是不好的做法,你最终会得到一个God 对象

The documentation on the Retrofit siteis fantastic, so I'm going to read your question on how to structure the project. I wrote a very small app for demonstration purposes. It loads cats from the cat API and should be fairly simple to follow what is happening.

Retrofit 网站上的文档非常棒,所以我将阅读您关于如何构建项目的问题。我写了一个非常小的应用程序用于演示目的。它从 cat API 加载猫,并且应该非常简单地了解正在发生的事情。

It has an example of using JSON or XML for the parsing of data from the service. You can find it at https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit

它有一个使用 JSON 或 XML 解析来自服务的数据的示例。您可以在https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit找到它

Hopefully you can extrapolate why I have structured it the way I have. I'm happy to answer any questions you have in the comments and update the answer.

希望你能推断出为什么我按照我的方式构建它。我很高兴回答您在评论中提出的任何问题并更新答案。

回答by Sean

Checkout this app that demonstrates Retrofit integration to Google Tasks API.

查看此应用程序,演示 Retrofit 与 Google Tasks API 的集成。

https://github.com/sschendel/SyncManagerAndroid-DemoGoogleTasks

https://github.com/sschendel/SyncManagerAndroid-DemoGoogleTasks

There are examples of Retrofit api (TaskApi) used within Activity AsyncTask in MainActivity, as well as examples of use within Sync Adapter in background service.

MainActivity的Activity AsyncTask里面有Retrofit api(TaskApi)的例子,也有后台服务Sync Adapter里面使用的例子。

The strategy from the article posted in @nPn's answer is probably a more elegant solution, but you can at least look at another working example.

@nPn 的回答中发布的文章中的策略可能是一个更优雅的解决方案,但您至少可以查看另一个工作示例。

回答by chkm8

I have just used retrofit for a couple of weeks and at first I found it hard to use in my application. I would like to share to you the easiest way to use retrofit in you application. And then later on if you already have a good grasp in retrofit you can enhance your codes(separating your ui from api and use callbacks) and maybe get some techniques from the post above.

我刚刚使用了几个星期的改造,起初我发现它很难在我的应用程序中使用。我想与您分享在您的应用程序中使用改造的最简单方法。然后,如果您已经很好地掌握了改造,您可以增强您的代码(将您的 ui 与 api 分开并使用回调),并且可能从上面的帖子中获得一些技术。

In your app you have Login,Activity for list of task,and activity to view detailed task.

在您的应用程序中,您有登录、任务列表的活动和查看详细任务的活动。

First thing is you need to add retrofit in your app and theres 2 ways, follow @artemis post above.

第一件事是你需要在你的应用程序中添加改造,有两种方法,按照上面的@artemis 帖子。

Retrofit uses interface as your API. So, create an interface class.

Retrofit 使用接口作为你的 API。所以,创建一个接口类。

public interface MyApi{

/*LOGIN*/
@GET("/api_reciever/login") //your login function in your api
public void login(@Query("username") String username,@Query("password") String password,Callback<String> calback); //this is for your login, and you can used String as response or you can use a POJO, retrofit is very rubust to convert JSON to POJO

/*GET LIST*/
@GET("/api_reciever/getlist") //a function in your api to get all the list
public void getTaskList(@Query("user_uuid") String user_uuid,Callback<ArrayList<Task>> callback); //this is an example of response POJO - make sure your variable name is the same with your json tagging

/*GET LIST*/
@GET("/api_reciever/getlistdetails") //a function in your api to get all the list
public void getTaskDetail(@Query("task_uuid") String task_uuid,Callback<Task> callback);   //this is an example of response POJO - make sure your variable name is the same with your json tagging

}

Create another interface class to hold all your BASE ADDRESS of your api

创建另一个接口类来保存 api 的所有基地址

public interface Constants{
   public String URL = "www.yoururl.com"
}

In your Login activity create a method to handle the retrofit

在您的登录活动中创建一个方法来处理改造

private void myLogin(String username,String password){

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(Constants.URL)  //call your base url
    .build();


MyApi mylogin = restAdapter.create(MyApi.class); //this is how retrofit create your api
mylogin.login(username,password,new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            //process your response if login successfull you can call Intent and launch your main activity

        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace(); //to see if you have errors
        }
    });
}

In your MainActivityList

在您的 MainActivityList 中

private void myList(String user_uuid){

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(Constants.URL)  //call your base url
    .build();


MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskDetail(user_uuid,new Callback<Task>>() {
        @Override
        public void success(ArrayList<Task> list, Response response) {
            //process your response if successful load the list in your listview adapter

        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace(); //to see if you have errors
        }
    });
}

In your Detailed List

在您的详细清单中

private void myDetailed(String task_uuid){

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(Constants.URL)  //call your base url
    .build();


MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskList(task_uuid,new Callback<Task>() {
        @Override
        public void success(Task task, Response response) {
            //process your response if successful do what you want in your task

        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace(); //to see if you have errors
        }
    });
}

Hope this would help you though its really the simplest way to use retrofit.

希望这会对您有所帮助,尽管它确实是使用改造的最简单方法。

回答by mr. Nutscracker

You may try saving references to your api inside your application class. Then you can get it's instance from any activity or fragment and get api from there. That sounds a little weird, but it may be a simple DI alternative. And if you will only store references in your app class, it won't be a kind of god object

您可以尝试在应用程序类中保存对 api 的引用。然后你可以从任何活动或片段中获取它的实例,并从那里获取 api。这听起来有点奇怪,但它可能是一个简单的 DI 替代方案。如果你只在你的应用类中存储引用,它就不会是一种上帝对象

UPD: http://square.github.io/retrofit/- here is some documentation, it might be useful

UPD:http: //square.github.io/retrofit/- 这里有一些文档,它可能有用

回答by kundan roy

Using RetroFit is very easy.

使用 RetroFit 非常简单。

  • Add dependecy in build.gradle.

        compile 'com.squareup.retrofit:retrofit:1.9.0'
    
        compile 'com.squareup.okhttp:okhttp:2.4.0' 
    
  • Make an Interface for all http methods.

  • Copy your json output and create pojo class to recieve json of your
    response, you can make pojo from JsonSchema2pojo site .

  • make an adapter and call your method

    for complete demo try this tutorial Retrofit Android example

  • 在 build.gradle 中添加依赖项。

        compile 'com.squareup.retrofit:retrofit:1.9.0'
    
        compile 'com.squareup.okhttp:okhttp:2.4.0' 
    
  • 为所有 http 方法创建一个接口。

  • 复制您的 json 输出并创建 pojo 类以接收您的
    响应的json ,您可以从JsonSchema2pojo站点制作 pojo 。

  • 制作一个适配器并调用您的方法

    要获得完整的演示,请尝试本教程Retrofit Android example

回答by Jawad Zeb

I find these tutorials AndroidHive, CodePathhelpful

我发现这些教程AndroidHiveCodePath很有帮助

I will briefly describe what I have learned.

我将简要描述我所学到的。

Step 1 :Add these three dependencies to build.gradleand Add Internet permissionto Manifest

第 1 步:添加这三个dependencies to build.gradle并添加Internet permissionManifest

compile 'com.google.code.gson:gson:2.6.2' // for string to class conversion. Not Compulsory
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion

Add them in Manifest

在清单中添加它们

<uses-permission android:name="android.permission.INTERNET" />

Step 2Creae ApiClient and ApiInterface.

步骤 2Creae ApiClient 和 ApiInterface。

public class ApiClient {

    public static final String BASE_URL = "http://yourwebsite/services/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

where ApiInterface.class

其中 ApiInterface.class

public interface ApiInterface {

    // getting same data in three different ways.
    @GET("GetCompanyDetailByID")
    Call<CompanyResponse> getDetailOfComapanies(@Query("CompanyID") int companyID);


    @GET("GetCompanyDetailByID")
    Call<ResponseBody> getRawDetailOfCompanies(@Query("CompanyID") int companyID);

    @GET("{pathToAdd}")
    Call<CompanyResponse> getDetailOfComapaniesWithPath(@Path("pathToAdd") String pathToAppend, @Query("CompanyID") int companyID);
}

And call this service like

并将此服务称为

ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapanies(2);
        //Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapaniesWithPath("GetCompanyDetailByID",2);

        companyResponseCall.enqueue(new Callback<CompanyResponse>() {
            @Override
            public void onResponse(Call<CompanyResponse> call, Response<CompanyResponse> response) {
                CompanyResponse comapnyResponse = response.body();
                Boolean status  = comapnyResponse.getStatus();
            }

            @Override
            public void onFailure(Call<CompanyResponse> call, Throwable t) {
            }
        });

For Getting Raw Json String

获取原始 Json 字符串

Call<ResponseBody> call = apiService.getRawDetailOfCompanies(2);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String jsonStr = response.body().string();
                    if(!jsonStr.isEmpty()){
                        Gson gson = new Gson();

                        JSONObject jObject = new JSONObject(jsonStr).getJSONObject("data");

                        //1st Method
                        Data dataKiType = gson.fromJson(jObject.toString(), Data.class);
                        dataKiType.getCompanyDetail();

                        //2nd method for creaing class or List at runTime
                        Type listType = new TypeToken<Data>(){}.getType();
                        Data yourClassList = new Gson().fromJson(jObject.toString(), listType);
                        yourClassList.getCompanyDetail();
                    }  e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

You can create your business object using http://www.jsonschema2pojo.org/by simply pasting json. and selecting source type to JSON and Annotation Style to GSon

您可以通过简单地粘贴 json使用http://www.jsonschema2pojo.org/创建您的业务对象。并选择源类型为 JSON 和注释样式为 GSon

回答by Madhav Bhattarai

Beginners find it little intimidating to learn retrofit. I have prepared a tutorial which will simplify the learning curve. See Retrofit android tutorialfor more information.

初学者发现学习改造并不可怕。我准备了一个教程,可以简化学习曲线。有关更多信息,请参阅Retrofit android 教程