如何使用快速的Android网络库在Android中显示Json结果

问题描述 投票:0回答:1

我正在使用快速Android网络库。 Json的回应正在发挥作用。我在logcat中得到了整个json字符串。如何在此库中的textview或listview中的textview或jsonarray中显示特定的json对象或字符串。请帮助,在此先感谢。

    JSONObject json = new JSONObject();

    try {
        json.put("email", loggedInUser);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.e("JSON", json.toString());

    AndroidNetworking.post(Constants.read_profile)
            .addBodyParameter("json", json.toString())
            .setTag("test")
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("READ", response.toString());


                }

                @Override
                public void onError(ANError anError) {
                    Log.e("READ", anError.toString());
                }
            });
java android json xml android-layout
1个回答
0
投票

尝试使用GSON进行json解析。我正在您现有的代码中实现GSON代码。

在app gradle实现'com.google.code.gson:gson:2.8.1'中添加此内容

对于JSONObject响应

getAsJSONObject(new JSONObjectRequestListener() {
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onResponse (JSONObject response){
        Log.e("READ", response.toString());

        if (response != null) {
            Gson gson = new Gson();
            Type type = new TypeToken<YourModelClass>() {
            }.getType();
            YourModelClass result = gson.fromJson(response.toString(), type);
        }
    }

    @Override
    public void onError (ANError anError){
        Log.e("READ", anError.toString());
    }
});

对于JSONArray响应

@Override
public void onResponse (JSONArray response){
    Log.e("READ", response.toString());

    if (response != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<YourModelClass>>() {
        }.getType();
        List<YourModelClass> result = gson.fromJson(response.toString(), type);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.