【问题标题】:Android code to fetch Json object and display获取 Json 对象并显示的 Android 代码
【发布时间】:2016-02-16 15:56:15
【问题描述】:

我的问题是我在 Rest Api 中有一个名为 name 的 Json 对象。登录/注册后,我需要获取它并在我的应用程序中的 textView15 字段中显示。我不知道获取和显示 Json。任何帮助都是不言而喻的。

API 是:

{
  "users": {
    "_id": "gcx8ksa4XepvYRyWH",
    "emails": [
      {
        "address": "selenium@gmail.com",
        "verified": false
      }
    ]
  },
  "user": {
    "_id": "wWHmKn5ciWAHZGt2m",
    "user_id": "gcx8ksa4XepvYRyWH",
    "name": "selenium@gmail.com",
    "hubs": [],
    "username": "selenium",
    "industry": "selenium",
    "profession": "selenium"
  }
}

我的代码:

 AsyncHttpClient client = new AsyncHttpClient();
        applyJobItems.clear();
        List<String> userCredentials = UserUtils.getLoginDetails();
        client.addHeader("x-user-id", userCredentials.get(0));
        client.addHeader("x-auth-token", userCredentials.get(1));
        client.get("https://", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                final String response = new String(responseBody);
                android.util.Log.e("Response", "" + response);

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    final JSONArray jsonArray = jsonObject.getJSONArray("user");


                    final List<String> names = new ArrayList<String>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject inter = new JSONObject(jsonArray.get(i).toString());
                        ApplyJobItem jobItem = new ApplyJobItem();
                        jobItem.setName(inter.getString("name"));
                        names.add(inter.getString("name"));
                        applyJobItems.add(jobItem);
                        android.util.Log.e("name", inter.getString("name"));
                    }
                }catch (Exception e) {
                        e.printStackTrace();
                    }

【问题讨论】:

  • Put,你在你的代码中尝试了什么然后询问查询,否则它会拒绝。

标签: android json rest jsonobject


【解决方案1】:

您可以使用 volley 轻松获取数据并渲染到视图中,如下所示...

登录后执行此代码...

List<Users> list = new ArratList<Users>();
CustomUserAdapter adapter;
JsonArrayRequest getJsonData = new JsonArrayRequest("<your_url>,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            Users mList = new Users();

                            JSONObject obj = response.getJSONObject(i);

                            JSONArray answers = obj.getJSONArray("emails");

                            long count = answers.length();
                            if(count > 0){
                                //setter methods
                            }

                            mList.setIDL(obj.getString("_id"));
                            list.add(mList);

                        } catch (JSONException e) {
                            Log.d("JSONError", e.toString());
                        }

                    }
                    adapter.notifyDataSetChanged();
                    //your listview findViewById().....
                    listView.setVisibility(View.VISIBLE);

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),"Error in fetchinf data",Toast.LENGTH_LONG).show();

        }
    });

    AppController.getInstance().addToRequestQueue(getJsonData);

volley的应用配置类(需要添加volley库)

了解更多关于凌空Get Volley

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {

    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

【讨论】:

    【解决方案2】:

    在android中的JSONObject变量中获取这个json并像这样解析它

    String name = jsonObject.getJSONObject('user').getString('name');
    

    这里jsonObject 是您从服务器获取的主要 json 对象的名称..

    编辑:Json 解析教程。

    这里是一些如何解析 json 的指南

    http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

    【讨论】:

      【解决方案3】:

      使用改造。它会为你做解析。

      http://square.github.io/retrofit/

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 2013-06-04
        • 2015-09-10
        • 2016-02-14
        • 2022-01-24
        • 2021-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多