如何在android中解析API响应? [英] How to Parse API response in android?

查看:61
本文介绍了如何在android中解析API响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何解析android中的响应?

How can we parse the response in android?

API 响应

{"id":29,"name":"demo","email":"demo@gmail.com"}

我如何获取 id、name 和 email 的值.

How can i get the value of id,name and email.

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://XXX.XX.X.XXX/api/api.php?apicall=login", params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
 prgDialog.hide();
 Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
 try {
   JSONObject jObj = new JSONObject(response);
   Toast.makeText(getApplicationContext(), jObj.getString("email"), Toast.LENGTH_LONG).show();
 } catch (JSONException e) {
   e.printStackTrace();
   Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
 }
}
});

推荐答案

像这样替换你的代码,这就是你需要解析的方式,如果你有多个对象,那么你必须使用循环.

Replace your code like this, This is how you need to parse if you have more than on object, then you have to use the loop.

 AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://XXX.XX.X.XXX/api/api.php?apicall=login", params, new TextHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String response) {
            prgDialog.hide();
            Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
            try {
                JSONObject reader = new JSONObject(response);
                int id  = reader.getInt("id");
                String name  = reader.getString("name");
                String email  = reader.getString("email");
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });

这篇关于如何在android中解析API响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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