使用API进行Android JSON解析

使用API进行Android JSON解析,android,json,digg,Android,Json,Digg,我很难弄清楚如何正确解析这个JSON文件 { "count": 10, "timestamp": 1333243153, "total": 100, "diggs": [ { "date": 1333243146, "item": { "status": "upcoming", "container": {

我很难弄清楚如何正确解析这个JSON文件

{
    "count": 10, 
    "timestamp": 1333243153, 
    "total": 100, 
    "diggs": [
        {
            "date": 1333243146, 
            "item": {
                "status": "upcoming", 
                "container": {
                    "name": "Politics", 
                    "short_name": "politics"
                }, 
                "description": "Major steps toward the disestablishment of Norway's state church, the (Lutheran) Church of Norway, were passed by the government on March 16 in its weekly session with King Harald V.", 
                "title": "National Secular Society - Norway continues the long process of disestablishing the Lutheran Church", 
                "submit_date": 1333206325, 
                "media": 0, 
                "diggs": 5, 
                "comments": 0, 
                "topic": {
                    "name": "Politics", 
                    "short_name": "politics"
                }, 
                "shorturl": {
                    "short_url": "http://digg.com/news/politics/national_secular_society_norway_continues_the_long_process_of_disestablishing_the_lutheran_church", 
                    "view_count": 0
                }, 
                "promote_date": null, 
                "link": "http://www.secularism.org.uk/news/2012/03/norway-continues-the-long-process-of-disestablishing-the-lutheran-church", 
                "href": "http://digg.com/news/politics/national_secular_society_norway_continues_the_long_process_of_disestablishing_the_lutheran_church", 
                "id": "20120331150525:56935e86-2dbf-4831-ad60-50def7781e68"
            }, 
            "user": {
                "name": "ghelms", 
                "links": [], 
                "registered": 1158007588, 
                "profileviews": 0, 
                "fullname": "Gary Helms", 
                "icon": "http://cdn2.diggstatic.com/user/614412/l.2001177284.png"
            }, 
            "digg_id": "20120401011907:5cf92ee9-e915-4358-b14f-cf140b760469"
        }, 
    ], 
    "offset": 0
 }
我试图只获取一些元素“日期”、“描述”、“标题”、“diggs”、“链接”和“digg\u id”。每当我尝试解析它时,它都不会在listView中工作,但如果我在GetMethod类中使用一个字符串,它会将整个API解析为一个字符串,并很好地打印出来

我的代码:

public DiggItemList lastDigg () throws Exception {
    ArrayList<HashMap<String,DiggItem>> diggsList = new  ArrayList<HashMap<String, DiggItem>>();
    JSONArray diggs = null;
    JSONObject json = null;
    Intent in = getIntent();
    String short_name = in.getStringExtra(TAG_SHORT_NAME);
    GetMethod get = new GetMethod();
    json = get.getInternetData();

    try {
        diggs = json.getJSONArray("diggs");

            dlists = new DiggItemList();
            for (int i = 0; i < diggs.length(); i++) {
                JSONObject c = diggs.getJSONObject(i);
                String date = c.getString("date");
                String description = c.getString("description");
                String title = c.getString("title");
                int digg = c.getInt("diggs");
                String link = c.getString("link");
                int digg_id = c.getInt("digg_id");

                //JSONObject topic = c.getJSONObject("topic");
                    //String sn = topic.getString("short_name");

                DiggItem di = new DiggItem();
                di.setDate(c.getInt("date"));
                di.setDescription(c.getString("description"));
                di.setTitle(c.getString("title"));
                di.setDiggs(c.getInt("diggs"));
                di.setLink(c.getString("link"));
                di.setDigg_id(c.getString("digg_id"));
                    dlists.add(di);
                    /*
                if (sn.equals(short_name)) {
                    dlists.add(di);
                }
                                */
            }

    }catch (JSONException e) {
        e.printStackTrace();
    }
    return dlists;
}

只是建议一个简单的方法来做想要的。。。 有关更多详细信息,请参阅并学习教程

public void parseData引发异常{
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpGet HttpGet=新的HttpGet(“http://services.digg.com/2.0/digg.getAll");
//执行请求
HttpResponse响应;
//获取响应实体
HttpEntity=response.getEntity();
//如果响应没有包含实体,则不需要
//担心连接释放
如果(实体!=null){
//一个简单的JSON响应读取
//InputStream instream=entity.getContent();
//字符串结果=convertStreamToString(流内).trim();
字符串结果=EntityUtils.toString(实体);
JsonObject json=新的JsonObject(结果);
JSONArray diggsJsonArray=json.getJSONArray(“diggs”);

对于代码日期中的(int i=0;i字符串类型,在“DiggItem di”中存储时,使用的是c.getInt(“date”),它是一个整数值。
此外,digg\u id不能是整数,因为作为响应,digg\u id的值是字母数字的组合,因此您也可以在此处使用字符串。

首先创建一个HTTP\u处理程序类

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}
然后创建一个私有类来获取数据

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Index.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("data");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject JO = (JSONObject) contacts.get(i);
                    /*if(JO.has("devices"))
                    {
                        Toast.makeText(Index.this,"No Data Found",Toast.LENGTH_LONG).show();
                    }*/
                    JSONObject jb = (JSONObject) JO.get("devices");

                    String id = jb.getString("user_id");
                    String trip_id = jb.getString("id");
                    String product = jb.getString("product");
                    String name = jb.getString("devices");
                    String start_geo = jb.getString("address");
                    String end_lat = jb.getString("Latitude");
                    String end_long = jb.getString("longitude");
                    //String gender = jb.getString("pointtopoint_estimate_id");


                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("trip_id", trip_id);
                    contact.put("product", product);
                    contact.put("name", name);
                    contact.put("start_geo", start_geo);
                    contact.put("end_lat",end_lat );
                    contact.put("end_long",end_long );

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Your Internet Connection is Weak. Try Reloading Your Page",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Check Your Internet Connection",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
}
}
私有类GetContacts扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=新建进度对话框(Index.this);
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
HttpHandler sh=新的HttpHandler();
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(url);
Log.e(标签,“来自url的响应:+jsonStr”);
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
//获取JSON数组节点
JSONArray contacts=jsonObj.getJSONArray(“数据”);
//通过所有触点循环
对于(int i=0;ivalue
联系人:put(“id”,id);
联系人。put(“跳闸id”,跳闸id);
联系人。放置(“产品”,产品);
联系人。填写(“姓名”,姓名);
联系人。put(“start\u geo”,start\u geo);
联系人。put(“end_lat”,end_lat);
联系人。put(“end_long”,end_long);
//将联系人添加到联系人列表
联系人列表。添加(联系人);
}
}捕获(最终JSONException e){
Log.e(标记“Json解析错误:”+e.getMessage());
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(getApplicationContext(),
“您的Internet连接很弱。请尝试重新加载您的页面”,
吐司长度(长)
.show();
}
});
}
}否则{
e(标记“无法从服务器获取json”);
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(getApplicationContext(),
“检查您的Internet连接”,
吐司长度(长)
.show();
}
});
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
//关闭进度对话框
if(pDialog.isShowing())
pDialog.disclose();
}
}
public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Index.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("data");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject JO = (JSONObject) contacts.get(i);
                    /*if(JO.has("devices"))
                    {
                        Toast.makeText(Index.this,"No Data Found",Toast.LENGTH_LONG).show();
                    }*/
                    JSONObject jb = (JSONObject) JO.get("devices");

                    String id = jb.getString("user_id");
                    String trip_id = jb.getString("id");
                    String product = jb.getString("product");
                    String name = jb.getString("devices");
                    String start_geo = jb.getString("address");
                    String end_lat = jb.getString("Latitude");
                    String end_long = jb.getString("longitude");
                    //String gender = jb.getString("pointtopoint_estimate_id");


                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("trip_id", trip_id);
                    contact.put("product", product);
                    contact.put("name", name);
                    contact.put("start_geo", start_geo);
                    contact.put("end_lat",end_lat );
                    contact.put("end_long",end_long );

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Your Internet Connection is Weak. Try Reloading Your Page",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Check Your Internet Connection",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
}
}