在Android中将JSON转换为数组有什么问题?

时间:2014-02-02 01:15:26

标签: android json try-catch

这是我项目中的MainActivity(仅限活动)(FSM,我知道)

public class MainActivity extends Activity {
    private static final String DEBUG_TAG = "HttpExample";
    private static final String MYURL = "http://www.myserver.com/myapp/usertable.php";
    private TextView textView;

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

        textView = (TextView) findViewById(R.id.hello_world);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        //Check connectivity
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            //fetch data
            new DownloadWebpageTask().execute(MYURL);
            textView.setText("Fetching data");


        } else {
            //show error
            textView.setText("No network connection available.");
        }
    }

    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
            textView.setMovementMethod(new ScrollingMovementMethod());
        }
    }

    //Method to convert url to url object
    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 16*1024; //Try 16*1024
        String username;
        String password;
        String email;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            Log.d(DEBUG_TAG, "The data is: " + contentAsString);

            try {
                //Get master array of locations
                Log.d(DEBUG_TAG, "BEFORE JSONArray: " + contentAsString);

                JSONArray jsonArray = new JSONArray(contentAsString);
                Log.d(DEBUG_TAG, "AFTER JSONArray: " + contentAsString);

                //Loop through each dictionary in array
                for (int i = 0; i < jsonArray.length(); i++) {
                    //test array contents
                    //String strToPrint = "jsonArray[" + i + "]=" + jsonArray[i];

                    //Get the lat&long for
                    JSONObject someData  = jsonArray.getJSONObject(i);
                    System.out.println(i + " id : " + someData.getString("id"));
                    System.out.println(i + " user : " + someData.getString("username"));
                    System.out.println(i + " email : " + someData.getString("email"));
                    //username = sys.getString("username");
                    //email = sys.getString("email");
                    //password = sys.getString("password");

                    //Create location object

                    // Use Location.distanceTo() - creates list of distances to users current location

                    //add distance to array?
                }

                //Sort and get nearest 5 locations


                //better use Mirror API
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("trycatch" );

                e.printStackTrace();
            }


            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    //Get distances
    public float distanceTo (Location dest) {

        //Compare distance passed to user location

        //return distance float
        return 1;
    }


    //Convert input stream to string
    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }

这是打印的最终结果,因为数据是:在一长串正确字符的末尾:

, “电子邮件”:“乔

服务器响应实际上是:

, “电子邮件”: “John.e.Francois@someserver.com”

以下是服务器结果的示例:

[{"id":"36","username":"Simulor","password":"0457e576192406775e574c2555e2edc6","password_hint":"","last name":"","first name":"","email":"info@hey.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2013-06-29 17:51:40","time_queued":null,"time_sent":null},
{"id":"35","username":"zlitsami ","password":"932d1c42a4e4880e57037994fd3584b1","password_hint":"","last name":"","first name":"","email":"sami@yahoo.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","idid":"9","userCreated":"2013-01-01 14:27:22","time_queued":null,"time_sent":null},{"id":"34","username":"Probate","password":"5fbba4aa93a00a9d75b19a3b7f9249bd","password_hint":"","last name":"","first name":"","email":"info@google.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2012-06-15 12:17:53","time_queued":null,"time_sent":null},{"id":"4","username":"carSim","password":"2d157441e6f311d0a5c8a5cbe2fd6f06","password_hint":"","lastname":"","firstname":"","email":"info@compusa.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"F6869FB4-2EBE-5D43-A62D-5D4007646764","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"33","username":"Test","password":"68eacb97d86f0c4621fa2b0e17cabd8c","password_hint":"","lastname":"","firstname":"","email":"info@openerp.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2012-06-15 12:03:49","time_queued":null,"time_sent":null},{"id":"6","username":"danni","password":"6d1ab84bf937dde5ef7d738f97b44314","password_hint":"","lastname":"","firstname":"","email":"jodri40@hotmail.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"36e83a379985ce9e485fdbd2d94d2c835f869b1c","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"7","username":"janevm","password":"da80a7e5f20f7dd56370dba9305155ef","password_hint":"","lastname":"","firstname":"","email":"cats5@hotmail.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"adead80b9f8426ff4c20b38f4aa8cca9ab75e383","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"8","username":"JohnFranks","password":"3cc5f0b88d4cf16008ed8f63c88ddcb0","password_hint":"","lastname":"","firstname":"","email":"John.e.Francois@somerserver.com","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","idid":"9950b4a6189f338eb68b38bd76745ef6a6d932f1","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"}
]

什么可能导致那些奇怪的人物?它们仅在我将Stream的int len设为此大小(16 * 1024)时才会出现。最初它只有500.但为什么我甚至需要指定一定数量的字符才能返回?

为什么应用程序永远不会超过JSONArray jsonArray = new JSONArray(contentAsString);线?

我可以使用JSON编码的数组,并将其直接放入java中的数组吗?

3 个答案:

答案 0 :(得分:1)

当id,username和email的值是字符串时,为什么要调用someData.getInt()/ sameData.getDouble()?你应该改为调用someData.getString()。

答案 1 :(得分:0)

您是否可以提供您的网络服务网址,以便我可以使用我的代码进行测试?

请为用户更改getDouble和&amp;电子邮件的getBoolean为getString,如下所示:

System.out.println(i + " user : " + someData.getString("username"));
System.out.println(i + " email : " + someData.getString("email"));

答案 2 :(得分:0)

我将读取InputStream的方法替换为:

public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

        //New code to convert InputStream to String
        String line;
        while ((line = reader.readLine()) != null) {
        builder.append(line);
        }
        return builder.toString();
    }

现在有效。