【问题标题】:Problems parsing JSON data解析 JSON 数据的问题
【发布时间】:2013-12-10 18:00:05
【问题描述】:

我已经搜索了一天的解决方案,但找不到适合我情况的解决方案。我很抱歉,但我是 JSON(自学程序员)的新手,我不知道我应该只发布哪些课程,所以我会投入我所拥有的一切。我从 LogCat 收到以下错误:

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray

这是我的课:

package com.example.mytravelbuddy;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Itinerary extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    //JSON Parser
    JSONParser jParser = new JSONParser();

    //URL To Get Products
    public static String url = "URL REMOVED"; //Removed my url since i was hosting online

    //JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_ITEMS = "items";
    private static final String TAG_ID = "ID";
    private static final String TAG_LOCATION = "Location";
    private static final String TAG_DESCRIPTION = "Description";
    private static final String TAG_LATITUDE = "Latitude";
    private static final String TAG_LONGITUDE = "Longitude";
    private static final String TAG_TIME = "Time";

    //Array list
    ArrayList<HashMap<String, String>> itemList;

    //Items JSONArray
    JSONArray items = null;


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

        itemList = new ArrayList<HashMap<String, String>>();

        new LoadAllItems().execute();
    }

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

    class LoadAllItems extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Itinerary.this);
            pDialog.setMessage("Loading items. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }


        @Override
        protected String doInBackground(String... arg0) {

            //Building Params
            List<NameValuePair> params = new ArrayList<NameValuePair>();        

            //Getting JSON String
            JSONObject json = jParser.makeHttpRequest(url, "GET", params);

            try{
                //Getting array of items
                Log.i("Error","ERROR 1"); //This error message is displayed
                items = json.getJSONArray(TAG_ITEMS); //This is the line that is giving me a problem
                Log.i("Error","ERROR 2"); //This error message is not displayed

                //Looping through
                for(int i = 0; i < items.length();i++){

                    JSONObject c = items.getJSONObject(i);

                    //Storing JSON item in variable
                    String location = c.getString(TAG_LOCATION);
                    String description = c.getString(TAG_DESCRIPTION);
                    String longitude = c.getString(TAG_LONGITUDE);
                    String latitude = c.getString(TAG_LATITUDE);
                    String time = c.getString(TAG_TIME);


                    //Creating HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    //Put value in hashmap map
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_DESCRIPTION, description);
                    map.put(TAG_LONGITUDE, longitude);
                    map.put(TAG_LATITUDE, latitude);
                    map.put(TAG_TIME, time);

                    itemList.add(map);
                }
            }catch(JSONException e){
                e.printStackTrace();
            }

            return null;
        }}
}

通过在 LogCat 中显示错误消息,我发现在哪一行出现错误。

这是我试图从中获取响应的 PHP 文件:

 <?php

$user = "root";
$pass = "";
$database = "travel_buddy";
$server = "127.0.0.1";

mysql_connect($server, $user, $pass);
    $db_found = mysql_select_db($database);
    if($db_found){
        echo"DB Found<br>";
    }else{
        echo"DB NOT Found<br>";
    }
echo"Connection Established<br>";
get_details();


function get_details(){
$response = array();
$result = mysql_query("SELECT *FROM adventure");

if(mysql_num_rows($result)>0){
    $response["items"] = array();

    while($row = mysql_fetch_array($result)){
        $info = array();
        $product["ID"] = $row["ID"];
        $product["Location"] = $row["Location"];
        $product["Description"] = $row["Description"];
        $product["Latitude"] = $row["Latitude"];
        $product["Longitude"] = $row["Longitude"];
        $product["Time"] = $row["Time"];

        array_push($response["items"], $product);
    }
        $response["success"] = 1;

        echo json_encode($response);
} else {
    $response["success"] = 0;
    $response["message"] = "No Information Found";

    echo json_encode($response);
}

}

?>

这是我的 JSON 响应:

{
    "items": [
        {
            "ID": "1",
            "Location": "TEST",
            "Description": "TEST DESC",
            "Latitude": "1",
            "Longitude": "2",
            "Time": "3:00"
        },
        {
            "ID": "2",
            "Location": "TEST2",
            "Description": "TEST2 DESC",
            "Latitude": "1",
            "Longitude": "1",
            "Time": "7:00"
        },
        {
            "ID": "3",
            "Location": "TEST3",
            "Description": "TEST3 DESC",
            "Latitude": "3",
            "Longitude": "4",
            "Time": "12:00"
        }
    ],
    "success": 1
}

这是我的 JSON 解析器类:

package com.example.mytravelbuddy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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<NameValuePair> 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;

    }
}

任何帮助都会非常有帮助,可能会解释为什么我会出现此错误,因此我不再重复。

【问题讨论】:

  • 您似乎收到的是 XML 而不是 JSON。
  • method == "GET" 也是错误的。比较字符串时使用.equals
  • 是的,我知道那部分。我不知道如何解决它?是不是我的数据库有问题?
  • @SotiriosDelimanolis 这是一个预制的解析器类...感谢您指出这一点:)
  • don't use mysql_* functions in new code。它们不再被维护并被正式弃用。改为了解prepared statements,并使用PDOMySQLithis article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial.

标签: java php android json


【解决方案1】:

php 页面正在回显其他字符串而不是 json(仅)。

【讨论】:

  • 解析前打印json字符串。
【解决方案2】:

我强烈建议使用Gson 来解析您的 JSON 响应。

对于上面的示例,该类将如下所示:

public class ItemList {
    List<Item> items;
}

Item 将是:

public class Item {
    private String ID;
    private String Location;
    private String Description;
    private String Longitude;
    private String Latitude;
    private String Time;
}

然后,解析变得非常简单。将 gson-2.2.4.jar 放入您的 libs 文件夹中,然后执行以下操作:

Gson GSON = new Gson();
ItemList itemList = GSON.fromJson(json_string_here, ItemList.class);

就是这样。您有一个从 JSON 解析的一流 java 对象。简单而强大。

【讨论】:

  • 如果我使用 Gson,我就不需要我的 Parser 类了吗?
  • 您仍然需要从任何服务它的服务器下载 JSON,但您不再需要使用 jObj = new JSONObject(json);
【解决方案3】:

这可能会导致问题

mysql_connect($server, $user, $pass);
    $db_found = mysql_select_db($database);
    if($db_found){
        echo"DB Found<br>";
    }else{
        echo"DB NOT Found<br>";
    }
echo"Connection Established<br>";

您的服务正在呼应其他事情。 它应该只回显 JSON。


相反,可以记录此类信息
mysql_connect($server, $user, $pass);
    $db_found = mysql_select_db($database);
    if($db_found){
        error_log("DB Found<br>");
    }else{
         error_log("DB NOT Found<br>)";
    }
error_log("Connection Established<br>");

标题也很重要:

header("Content-Type: application/json");

将它放在脚本的顶部。

编辑: 我刚刚试过你的代码,我可以正确解析 JSON。

很可能您的 PHP 服务器出于某种原因正在发送 XML。您需要再次检查该脚本。 甚至可能是错误报告弄乱了您的编码 json,记录任何错误但只回显 JSON。

希望这会有所帮助。

【讨论】:

  • 我更改了这些行,但我的应用程序仍然崩溃并出现同样的错误。
  • @user2904544 我只是试试你的代码,它的工作很完美,你必须对 PHP 进行故障排除,它没有正确地回显 JSON
  • 问题可能是因为我从表中返回了 2 个浮点数(经度和纬度)?
  • @user2904544 不,因为你把它放在引号里,所以 JSON 会把它当作一个字符串,你应该真正调试 PHP,尝试将所有内容注释掉,你可以硬编码 JSON 数据并回显,然后一点一点地取消注释你的代码,你知道基本的调试。
猜你喜欢
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
相关资源
最近更新 更多