【问题标题】:Get JSON array from retrofit Response从改造响应中获取 JSON 数组
【发布时间】:2016-03-23 12:55:03
【问题描述】:

我需要从 Retrofit 解析 JSON 数组。我需要得到以下密钥:

{
  "rc":0,
  "message":"success",
  "he":[
    {
      "name":"\u05de\u05e4\u05e7\u05d7",
      "type":0
    }
  ]
}

我可以轻松获取消息,但无法从响应中获取“he”数组。

这是我的数据模型类

public class GetRoleData implements Serializable {

    @SerializedName("he")

    private ArrayList<Roles> he;

    @SerializedName("message")
    private String message;

    public GetRoleData() {
        this.he = new ArrayList<>();
        this.message = "";
    }

    public ArrayList<Roles> getUserRoles() {
        return he;
    }

    public String getMessage() {
        return message;
    }

    public class Roles {

        public Roles() {
            name = "";
            type = -1;
        }

        @SerializedName("name")

        private String name;
        @SerializedName("type")

        private int type;

        public int getType() {
            return type;
        }

        public String getName() {
            return name;
        }

    }
}

这就是我向服务器发送请求的方式:

@POST("index.php/")
Call<GetRoleData> getUserRoles(@Body SetParams body);

这是我发送请求和处理响应的方式

APIService apiService = retrofit.create(APIService.class);

        Call<GetRoleData > apiCall = apiService.getUserRoles(params);
        apiCall.enqueue(new Callback<GetRoleData >() {


            @Override
            public void onResponse(retrofit.Response<GetRoleData > mUserProfileData, Retrofit retrofit) {

                Log.e("locale info", "mUserProfileData = " + mUserProfileData.body().toString());
                if (pDialog != null) {
                    pDialog.dismiss();
                }
                if (mUserProfileData.body().getMessage().equals("success")) {

                    Log.e("locale info", "user roles = " + mUserProfileData.body().getUserRoles().size());

                } else {
                    Toast.makeText(RegisterActivity.this, getResources().getString(R.string.get_role_error), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable t) {

                if (pDialog != null) {
                    pDialog.dismiss();
                }

                t.printStackTrace();
            }
        });

我想要什么

我需要从上面的响应中获取“he”数组。请帮忙谢谢。

这是我得到的回应..

【问题讨论】:

  • 请将代码粘贴到您发出请求并处理响应的位置
  • @vipinagrahari 请检查。
  • I am not able to get "he" array from response 到底是什么意思?
  • 你检查了我需要解析的响应吗?我需要从响应中获取 jsonArray,即“他”@Yazan
  • @Yazan 请检查更新的问题。我想获取“他”中的数据

标签: android arrays retrofit


【解决方案1】:

改造 2.0-beta2 的更新:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.code.gson:gson:2.4'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    // compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
}

界面:

@GET("/api/values")
Call<GetRoleData> getUserRoles();

MainActivity 的 onCreate:

        // Retrofit 2.0-beta2
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_URL_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        WebAPIService service = retrofit.create(WebAPIService.class);

        // Asynchronous Call in Retrofit 2.0-beta2
        Call<GetRoleData> call = service.getUserRoles();
        call.enqueue(new Callback<GetRoleData>() {
            @Override
            public void onResponse(Response<GetRoleData> response, Retrofit retrofit) {
                ArrayList<GetRoleData.Roles> arrayList = response.body().getUserRoles();
                if (arrayList != null) {
                    Log.i(LOG_TAG, arrayList.get(0).getName());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.e(LOG_TAG, t.toString());
            }
        });

改造 1.9

我使用你的GetRoleData

界面:

public interface WebAPIService {        

    @GET("/api/values")
    void getUserRoles(Callback<GetRoleData> callback);                       
}

主活动:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);            

        // creating a RestAdapter using the custom client
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL_BASE)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setClient(new OkClient(mOkHttpClient))
                .build();

        WebAPIService webAPIService = restAdapter.create(WebAPIService.class);

        Callback<GetRoleData> callback = new Callback<GetRoleData>() {
            @Override
            public void success(GetRoleData getRoleData, Response response) {
                String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
                Log.i(LOG_TAG, bodyString);
            }

            @Override
            public void failure(RetrofitError error) {
                String errorString = error.toString();
                Log.e(LOG_TAG, errorString);
            }
        };

        webAPIService.getUserRoles(callback);
    }

截图如下:

【讨论】:

  • 什么是我在改造中找不到的 RestAdapter。
  • 我使用的是 Retrofit 1.9,而不是 2.0 beta,compile 'com.squareup.retrofit:retrofit:1.9.0'
  • Ver 2.0,请注意RestAdapter 现在也重命名为Retrofitstackoverflow.com/questions/32424184/…
  • 切换回 1.9.0 后。仍然 Readapter 无法解决
  • 谢谢..我得到了错误......实际上我正在做我需要做的......客户没有提供完整的api信息..有时我得到“他”作为 JSONArray 和一些“en”作为 JSONArray。现在我使用邮递员点击网址然后我意识到错误。谢谢。当我需要帮助时,你就在那里。再次感谢。
【解决方案2】:

Mocky 测试 -> http://www.mocky.io/v2/567275072500008d0e995b2c 我正在使用 Retrofit 2 (beta-2)。这对我有用,没什么特别的:

调用定义:

@GET("/v2/567275072500008d0e995b2c")
Call<Base> getMock();

型号:

public class Base {
    public int rc;
    public String message;
    public List<Role> he;
}

public class Role {
    public String name;
    public int type;
}

改造:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

调用执行:

webservice.getMock().enqueue(new Callback<Base>() {
    @Override
    public void onResponse(Response<Base> response, Retrofit retrofit) {

    }

    @Override
    public void onFailure(Throwable t) {

    }
});

【讨论】:

  • 它对我不起作用..虽然它是我正在做的代码
  • 在我的模拟链接上测试你的代码,将模型更改为我的版本等。一定有一个小错误。
  • 嗯好吧让我试试。
  • 我收到了你的嘲笑的回应。那么我的情况有什么问题吗?
  • 所以服务器响应肯定有问题。将 HttpLoggingInterceptor 添加到您的客户端 (tutorial) 并检查 logcat 您到底收到了什么。可能是编码有问题,或者你得到的不是“he”jsonArray,而是“he”jsonObject。很难说。
【解决方案3】:

除了he 之外,您已经正确编写了所有的getter。为了让 Retrofit 解析您的 JSON 文件,您应该为 he 变量编写 getter,如下所示。

public ArrayList<Roles> getHe() {
    return he;
}

另外,尝试从构造函数中删除新的 ArrayList。

public GetRoleData() {
    // this.he = new ArrayList<>(); // <-- Remove here
    this.message = "";
}

【讨论】:

  • 你能写吗?
  • 我已经写在我的回答中了。除了变量之外,您已经以正确的格式编写了所有 getter。您需要将其编写为 getHe(而不是 getUserRoles),以便 Retrofit 解析 JSON 格式。
  • 把getRoles改成getHe()还是没有成功。
  • 你是不是得到了他以外的数据,还是接收不到 response.body() ?
  • 请尝试从构造函数中删除 arraylist 初始化。查看我的更新答案@MustanserIqbal
【解决方案4】:

// 使用以下 Pojo 类

public class GetRoleData {

@SerializedName("rc")
@Expose
private Integer rc;
@SerializedName("message")
@Expose
private String message;
@SerializedName("he")
@Expose
private List<He> he = new ArrayList<He>();

/**
*
* @return
* The rc
*/
public Integer getRc() {
return rc;
}

/**
*
* @param rc
* The rc
*/
public void setRc(Integer rc) {
this.rc = rc;
}

/**
*
* @return
* The message
*/
public String getMessage() {
return message;
}

/**
*
* @param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}

/**
*
* @return
* The he
*/
public List<He> getHe() {
return he;
}

/**
*
* @param he
* The he
*/
public void setHe(List<He> he) {
this.he = he;
}

}
-----------------------------------com.example.He.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;


public class He {

@SerializedName("name")
@Expose
private String name;
@SerializedName("type")
@Expose
private Integer type;

/**
*
* @return
* The name
*/
public String getName() {
return name;
}

/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

/**
*
* @return
* The type
*/
public Integer getType() {
return type;
}

/**
*
* @param type
* The type
*/
public void setType(Integer type) {
this.type = type;
}

}

【讨论】:

  • 没有成功......它和我的代码一样......你的代码有什么不同
  • 您在日志中得到什么响应
  • 我收到成功消息,但没有他的数据
  • 您是否在改造 Builder 中添加了转换器? .addConverterFactory(GsonConverterFactory.create());
  • 是的,我做了这个改造 = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .build();
【解决方案5】:

另一种使用 webservices 获取数据的简单方法是使用JsonElement,然后将其转换为 JsonObject 并解析 JsonObject。 Ez-Pz。

注意:JsonObject 与 JSONobject 不同,JsonObject 属于 GSON 的库

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2017-07-26
    • 2017-04-19
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多