繁体   English   中英

Android Studio解析JSON

[英]Android Studio parsing JSON

我正在尝试开发一个Android应用程序,该应用程序将连接到外部服务器以获取数据。 我已经成功读取了.php文件中的数据,但是由于抛出错误,因此无法在我的应用中使用它。

<?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));

?>

那就是我用来读取数据的php代码。 这是我在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;
}

这是JSONParser类:

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;

    }
}

这是JSON的结果:

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

错误是:

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

我真的需要帮助 先感谢您。

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

return json_decode(jObj);

在后台方法中重做json对象

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;

据我所知,该错误是在JSONParser类中最具体地抛出:

try {
            jObj = new JSONObject(json);


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

我终于将输出编码为[{“ Test”:“ Name1”}],现在我的错误已更改为解析数据org.json.JSONException的错误:org类型的值[{“ Test”:“ Name1”}]]。 json.JSONArray无法转换为JSONObject

如果您可以使用mysql发布相同的.php代码,我将不胜感激,因为我尝试编写它,但是它说“ mysql已过时”,而且我不知道如何使用mysqli。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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