如何在Android中解析JSON数组字符串

时间:2013-06-25 22:58:15

标签: android json

不幸的是,我不能说太多,只是它失败了。我正在尝试了解如何解析Android的JSON数组。以下是我现在的情况。我敢肯定,没有接近工作的地方。我已经尝试过断点,看看它到底出了什么问题,但它没有那么远。

我的代码:

package com.example.testers;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    private final String USER_AGENT = "Mozilla/5.0";

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

        JSONArray mJsonArray = null;
        try {
            mJsonArray = new JSONArray(sendGet());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject mJsonObject = new JSONObject();
        for (int i = 0; i < mJsonArray.length(); i++) {
            try {
                mJsonObject = mJsonArray.getJSONObject(i);
                mJsonObject.getString("id");
                mJsonObject.getString("title");
                mJsonObject.getString("post");
                mJsonObject.getString("author");
                mJsonObject.getString("tags");
                mJsonObject.getString("datePosted");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private String sendGet() throws Exception {

        String url = "http://www.craftbrothers.net/news/app.php";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        return response.toString();

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());

    }


}

1 个答案:

答案 0 :(得分:0)

首先,您没有使用您尝试从JSON响应中解析的值执行任何操作。当你打电话

mJsonObject.getString(String)

您没有将getString()结果分配给任何内容,因此您肯定不会在您的用户界面或任何日志中看到它。

此外,在UI线程( aka 主线程)上调用MainActivity#onCreate()You shouldn't perform network operations on the main thread,因为它会阻止用户的用户界面(冻结)。

您通常应使用AsyncTask之类的内容在后台执行网络请求,然后在任务的onPostExecute()方法中将结果显示给用户界面。

根据您运行的Android版本,如果您在UI线程上发出此请求,系统实际上可能会抛出exception