使用Retrofit库获取简单的JSON对象响应 [英] Getting simple JSON object response using Retrofit library

查看:135
本文介绍了使用Retrofit库获取简单的JSON对象响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有JSON响应的网络查询,

I have a web query with JSON response as:

{
    "status":true,
    "result":
      {
        "id":"1",
        "name":"ABC 1",
        "email":"info@ABc.dcom",
        "password":"123456",
        "status":false,
        "created":"0000-00-00 00:00:00"
      },
    "message":"Login successfully"
}

我将以下代码用于:

@GET("/stockers/login")
public void login(
        @Query("email") String email,
        @Query("password") String password,
        Callback<JSONObject> callback);

在Debugger中,由Retrofit库进行的查询是正确的,但是我得到一个空的JSON作为响应.

In Debugger the query made by the Retrofit library is correct, however I get an empty JSON in response.

ApiManager.getInstance().mUrlManager.login(
        email.getText().toString().trim(),
        password.getText().toString().trim(),
        new Callback<JSONObject>()
        {
            @Override
            public void success(JSONObject jsonObj, Response response)
            {
                mDialog.dismiss();

推荐答案

您可以使用Retrofit基本回调(而不使用JSONObject类进行回调),而该基本回调使用Response类,然后,一旦获得响应,就必须创建JSONObject.

Instead of Callback with JSONObject class, you could use the Retrofit basic callback which use the Response class and then, once you get the response, you had to create the JSONObject from it.

查看此: https://stackoverflow.com/a/30870326/2037304

否则,您可以创建自己的模型类来处理响应.

Otherwise you can create your own model class to handle the response.

首先是Result类:

First the Result class:

public class Result {
    public int id;
    public String name;
    public String email;
    public String password;
    public boolean status;
    public Date created;
}

然后将您的响应类与Retrofit一起使用

And then your response class to use with Retrofit

public class MyResponse {
    public boolean status;
    public Result result;
    public String message;
}

现在您可以致电:

 @GET("/stockers/login") 
 public void login( 
    @Query("email") String email,
    @Query("password") String password,
    Callback<MyResponse> callback);

这篇关于使用Retrofit库获取简单的JSON对象响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆