java - Android - 来自服务器的 JSON 为空

标签 java android json

我正在尝试从服务器获取 JSON 形式的一些数据。我不知道为什么,但我收到的数据是空的。该文件可通过以下链接访问:

http://andreid.imcserver.ro/test/service.php

服务器端代码非常简单:

<?php

// Create connection
$con=mysqli_connect("localhost","*****","*****","******");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// --------- This code is just for testing ---------
$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLon"];
$maxLon = $_REQUEST["maxLon"];

$file_handle = fopen("testFile.txt", "w");
$file_contents = $_POST;

fwrite($file_handle, $minLat);
fwrite($file_handle, $maxLat);
fwrite($file_handle, serialize($file_contents));
fclose($file_handle);

// ---------------------------------------------

$sql = "SELECT * FROM articolePeHarta";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{

    $resultArray = array();
    $tempArray = array();

    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    echo "{ \"posts\": ";
    echo json_encode($resultArray);
    echo "}";
}

// Close connections
mysqli_close($con);
?>

我现在使用的代码(我已经尝试了几种替代方案)是这个:

ArrayList<Article> articole = new ArrayList<Article>();

JSONArray finalResult;

// url to get all products list
private static String url_all_products = "http://andreid.imcserver.ro/test/service.php";

BufferedReader reader = null;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Loading products in Background Thread
        new LoadAllArticles().execute();

    }

...

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllArticles extends AsyncTask<String, String, String> {
    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {

        // Building Parameters
        List<ContentValues> params = new ArrayList<ContentValues>();
        //params.add(new BasicNameValuePair());
        // getting JSON string from URL
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url_all_products);
        //JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        try{
            HttpResponse response = client.execute(httppost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if ( statusCode == 200){
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                reader = new BufferedReader(new InputStreamReader(content));

                StringBuilder builder = new StringBuilder();
                for (String line = null; (line = reader.readLine()) != null;) {
                    Log.e("------------->",line);
                    builder.append(line).append("\n");
                }
                JSONTokener tokener = new JSONTokener(builder.toString());
                finalResult = new JSONArray(tokener);

                // looping through All Products
                for (int i = 0; i < finalResult.length(); i++) {
                    JSONObject c = finalResult.getJSONObject(i);

                    // Storing each json item in variable
                    String title = c.getString(TAG_TITLE);
                    String subTitle = c.getString(TAG_DETAILS);

                    Article art = new Article(title,subTitle);
                    articole.add(articole.size(),art);
                }

            }else {
                Log.e("====>", "Fail to download file");
            }

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

        return null;
    }

    protected void onPostExecute(String file_url) {

        if(reader!=null) {
            showDialog(MapsActivity.this,"It worked", reader.toString());
        }
        else{
            showDialog(MapsActivity.this,"Sorry", "Hai Rapid!");
        }

        showDialog(MapsActivity.this,"Rapid",String.valueOf( articole.size()));

        for (int i = 0; i < articole.size(); i++){
            showDialog(MapsActivity.this,"Hai Rapid!", articole.get(i).articleTitle);
        }

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {

            }
        });
    }
}

问题是文章没有元素...我做错了什么?

非常感谢您的帮助!

最佳答案

这一行的错误

finalResult = new JSONArray(tokener);

这不是一个 jsonArray 它是 json 对象

将其替换为以下内容。

JSONObject job = new JSONObject(tokener);

并像这样创建循环

for (int i = 0; i < job.length(); i++) {
                         Log.e("json object", job.getString("posts"));
//Do whatever you want here
//Feetch the data from json object

                     }

关于java - Android - 来自服务器的 JSON 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780100/

相关文章:

java - java中的锁重入是做什么用的?

java.net.SocketException : Connection Reset. 如何停止这个?

Java/clojure : Multiple character delimiter, 并保留分隔符

android - Qt Necessitas 错误 - 找不到 Ministro 服务

android - 双android版本的eclipse结构

java - StringBuffer找到 'start'和 'end'并在它们之间写入任何内容

android - 使用 RecyclerView 上的多个单选按钮的单选按钮

javascript - Html 将 json 值插入元素并将其转换为对象

python - 使用 Python 的 Flask 和 jsonpickle 获取 JSON 中不需要的转义字符

json - 是否可以 'inject' 引用 JSON 架构