简体   繁体   中英

Android Studio parsing JSON

Im trying to develope an android app which will connect to an external server to get the data. I have successfully read the data with my .php file but I can't use it in my app because it throws an error.

<?php

/**
 * A class file to connect to database
*/


// connect to database
try {
$pdo = new PDO('mysql:host=localhost;dbname=myDBname',' user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $err) {
die($err->getMessage());
}

$stmt = $pdo->prepare("select * from Test");


$result = $stmt->execute();
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));

?>

That's the php code I use to read the data. And this is the code I use in Android Studio

protected String doInBackground(String... args) {
            // Building Parameters
            List params = new ArrayList();
            // getting JSON string from URL

            JSONObject json = jParser.makeHttpRequest(server_php_url, "GET", params);
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    //Log.i("ramiro", "produtos.length" + products.length());
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable

                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap map = new HashMap();

                        // adding each child node to HashMap key => value

                        map.put(TAG_NAME, name);

                        empresaList.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
}

This is JSONParser class:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

This is the result of JSON:

Array ( [0] => Array ( [Test] => Name1 ) [1] => Array ( [Name] => Name2 ) )

The error is :

E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Array of type java.lang.String cannot be converted to JSONObject

I really need help. Thank you in advance.

在返回变量中使用json_decode(),您将获得json格式的输出,如下所示:

return json_decode(jObj);

Retrun json object in do in background method

protected String doInBackground(String... args) {
        // Building Parameters
        List params = new ArrayList();
        // getting JSON string from URL

        JSONObject json = jParser.makeHttpRequest(server_php_url, "GET", params);
        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                //Log.i("ramiro", "produtos.length" + products.length());
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable

                    String name = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap map = new HashMap();

                    // adding each child node to HashMap key => value

                    map.put(TAG_NAME, name);

                    empresaList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;

As far as I know the error is thrown in JSONParser class most specifically in :

try {
            jObj = new JSONObject(json);


        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

I have finally encoded the output to [{"Test":"Name1"}] and now my error has changed to Error parsing data org.json.JSONException: Value [{"Test":"Name1"}] of type org.json.JSONArray cannot be converted to JSONObject

I would apreciate if you could post the same .php code with mysql because I have tried to write it but it says "mysql is deprecated" and I dont know how to do it with mysqli.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM