在java中解析JSON数据时出错


Error parsing JSON data in java

我已经搜索了一天的解决方案,但找不到适合我情况的解决方案。很抱歉,我是JSON(自学程序员)的新手,我不知道我应该只发布什么类,所以我会把我所有的东西都放进去。我从LogCat得到以下错误:

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

这是我的课:

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

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();
        $info["ID"] = $row["ID"];
        $info["Location"] = $row["Location"];
        $info["Description"] = $row["Description"];
        $info["Latitude"] = $row["Latitude"];
        $info["Longitude"] = $row["Longitude"];
        $info["Time"] = $row["Time"];
        array_push($response["items"], $info);
    }
        $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值?

12-10 15:17:42.975: I/sb.toString()(2589): <?xml version="1.0" encoding="iso-8859-1"?>
12-10 15:17:42.975: I/sb.toString()(2589): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
12-10 15:17:42.975: I/sb.toString()(2589):  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
12-10 15:17:42.975: I/sb.toString()(2589): <html lang="en" xml:lang="en">
12-10 15:17:42.975: I/sb.toString()(2589): <head>
12-10 15:17:42.975: I/sb.toString()(2589):  <title>WAMPSERVER Homepage</title>
12-10 15:17:42.975: I/sb.toString()(2589):  <meta http-equiv="Content-Type" content="txt/html; charset=utf-8" />
12-10 15:17:42.975: I/sb.toString()(2589):  <style type="text/css">
12-10 15:17:42.975: I/sb.toString()(2589): * {
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 0;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): html {
12-10 15:17:42.975: I/sb.toString()(2589):  background: #ddd;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): body {
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 1em 10%;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 1em 3em;
12-10 15:17:42.975: I/sb.toString()(2589):  font: 80%/1.4 tahoma, arial, helvetica, lucida sans, sans-serif;
12-10 15:17:42.975: I/sb.toString()(2589):  border: 1px solid #999;
12-10 15:17:42.975: I/sb.toString()(2589):  background: #eee;
12-10 15:17:42.975: I/sb.toString()(2589):  position: relative;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): #head {
12-10 15:17:42.975: I/sb.toString()(2589):  margin-bottom: 1.8em;
12-10 15:17:42.975: I/sb.toString()(2589):  margin-top: 1.8em;
12-10 15:17:42.975: I/sb.toString()(2589):  padding-bottom: 0em;
12-10 15:17:42.975: I/sb.toString()(2589):  border-bottom: 1px solid #999;
12-10 15:17:42.975: I/sb.toString()(2589):  letter-spacing: -500em;
12-10 15:17:42.975: I/sb.toString()(2589):  text-indent: -500em;
12-10 15:17:42.975: I/sb.toString()(2589):  height: 125px;
12-10 15:17:42.975: I/sb.toString()(2589):  background: url(index.php?img=gifLogo) 0 0 no-repeat;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): .utility {
12-10 15:17:42.975: I/sb.toString()(2589):  position: absolute;
12-10 15:17:42.975: I/sb.toString()(2589):  right: 4em;
12-10 15:17:42.975: I/sb.toString()(2589):  top: 145px;
12-10 15:17:42.975: I/sb.toString()(2589):  font-size: 0.85em;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): .utility li {
12-10 15:17:42.975: I/sb.toString()(2589):  display: inline;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): h2 {
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0.8em 0 0 0;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): ul {
12-10 15:17:42.975: I/sb.toString()(2589):  list-style: none;
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 0;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): #head ul li, dl ul li, #foot li {
12-10 15:17:42.975: I/sb.toString()(2589):  list-style: none;
12-10 15:17:42.975: I/sb.toString()(2589):  display: inline;
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 0 0.2em;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): ul.aliases, ul.projects, ul.tools {
12-10 15:17:42.975: I/sb.toString()(2589):  list-style: none;
12-10 15:17:42.975: I/sb.toString()(2589):  line-height: 24px;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): ul.aliases a, ul.projects a, ul.tools a {
12-10 15:17:42.975: I/sb.toString()(2589):  padding-left: 22px;
12-10 15:17:42.975: I/sb.toString()(2589):  background: url(index.php?img=pngFolder) 0 100% no-repeat;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): ul.tools a {
12-10 15:17:42.975: I/sb.toString()(2589):  background: url(index.php?img=pngWrench) 0 100% no-repeat;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): ul.aliases a {
12-10 15:17:42.975: I/sb.toString()(2589):  background: url(index.php?img=pngFolderGo) 0 100% no-repeat;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): dl {
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 0;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): dt {
12-10 15:17:42.975: I/sb.toString()(2589):  font-weight: bold;
12-10 15:17:42.975: I/sb.toString()(2589):  text-align: right;
12-10 15:17:42.975: I/sb.toString()(2589):  width: 11em;
12-10 15:17:42.975: I/sb.toString()(2589):  clear: both;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): dd {
12-10 15:17:42.975: I/sb.toString()(2589):  margin: -1.35em 0 0 12em;
12-10 15:17:42.975: I/sb.toString()(2589):  padding-bottom: 0.4em;
12-10 15:17:42.975: I/sb.toString()(2589):  overflow: auto;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): dd ul li {
12-10 15:17:42.975: I/sb.toString()(2589):  float: left;
12-10 15:17:42.975: I/sb.toString()(2589):  display: block;
12-10 15:17:42.975: I/sb.toString()(2589):  width: 16.5%;
12-10 15:17:42.975: I/sb.toString()(2589):  margin: 0;
12-10 15:17:42.975: I/sb.toString()(2589):  padding: 0 0 0 20px;
12-10 15:17:42.975: I/sb.toString()(2589):  background: url(index.php?img=pngPlugin) 2px 50% no-repeat;
12-10 15:17:42.975: I/sb.toString()(2589):  line-height: 1.6;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): a {
12-10 15:17:42.975: I/sb.toString()(2589):  color: #024378;
12-10 15:17:42.975: I/sb.toString()(2589):  font-weight: bold;
12-10 15:17:42.975: I/sb.toString()(2589):  text-decoration: none;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): a:hover {
12-10 15:17:42.975: I/sb.toString()(2589):  color: #04569A;
12-10 15:17:42.975: I/sb.toString()(2589):  text-decoration: underline;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): #foot {
12-10 15:17:42.975: I/sb.toString()(2589):  text-align: center;
12-10 15:17:42.975: I/sb.toString()(2589):  margin-top: 1.8em;
12-10 15:17:42.975: I/sb.toString()(2589):  border-top: 1px solid #999;
12-10 15:17:42.975: I/sb.toString()(2589):  padding-top: 1em;
12-10 15:17:42.975: I/sb.toString()(2589):  font-size: 0.85em;
12-10 15:17:42.975: I/sb.toString()(2589): }
12-10 15:17:42.975: I/sb.toString()(2589): </style>
12-10 15:17:42.975: I/sb.toString()(2589):     
12-10 15:17:42.975: I/sb.toString()(2589):  <link rel="shortcut icon" href="index.php?img=favicon" type="image/ico" />
12-10 15:17:42.975: I/sb.toString()(2589): </head>
12-10 15:17:42.975: I/sb.toString()(2589): <body>
12-10 15:17:42.975: I/sb.toString()(2589):  <div id="head">
12-10 15:17:42.975: I/sb.toString()(2589):      <h1><abbr title="Windows">W</abbr><abbr title="Apache">A</abbr><abbr title="MySQL">M</abbr><abbr title="PHP">P</abbr></h1>
12-10 15:17:42.975: I/sb.toString()(2589):      <ul>
12-10 15:17:42.975: I/sb.toString()(2589):          <li>PHP 5</li>
12-10 15:17:42.975: I/sb.toString()(2589):          <li>Apache 2</li>
12-10 15:17:42.975: I/sb.toString()(2589):          <li>MySQL 5</li>
12-10 15:17:42.975: I/sb.toString()(2589):      </ul>
12-10 15:17:42.975: I/sb.toString()(2589):  </div>
12-10 15:17:42.975: I/sb.toString()(2589):  <ul class="utility">
12-10 15:17:42.975: I/sb.toString()(2589):      <li>Version 2.4
12-10 15:17:42.975: I/sb.toString()(2589): </li>
12-10 15:17:42.975: I/sb.toString()(2589):      <li><a href="?lang=fr">Version Fran&ccedil;aise</a></li>
12-10 15:17:42.975: I/sb.toString()(2589):  </ul>
12-10 15:17:42.975: I/sb.toString()(2589):  <h2> Server Configuration </h2>
12-10 15:17:42.975: I/sb.toString()(2589):  <dl class="content">
12-10 15:17:42.975: I/sb.toString()(2589):      <dt>Apache Version :</dt>
12-10 15:17:42.975: I/sb.toString()(2589):      <dd>2.4.4
12-10 15:17:42.975: I/sb.toString()(2589):  &nbsp;</dd>
12-10 15:17:42.975: I/sb.toString()(2589):      <dt>PHP Version :</dt>
12-10 15:17:42.975: I/sb.toString()(2589):      <dd>5.4.16
12-10 15:17:42.975: I/sb.toString()(2589):  &nbsp;</dd>
12-10 15:17:42.975: I/sb.toString()(2589):      <dt>Loaded Extensions : </dt> 
12-10 15:17:42.975: I/sb.toString()(2589):      <dd>
12-10 15:17:42.975: I/sb.toString()(2589):          <ul>
12-10 15:17:42.975: I/sb.toString()(2589):          <li>Core</li><li>bcmath</li><li>calendar</li><li>ctype</li><li>date</li><li>ereg</li><li>filter</li><li>ftp</li><li>hash</li><li>iconv</li><li>json</li><li>mcrypt</li><li>SPL</li><li>odbc</li><li>pcre</li><li>Reflection</li><li>session</li><li>standard</li><li>mysqlnd</li><li>tokenizer</li><li>zip</li><li>zlib</li><li>libxml</li><li>dom</li><li>PDO</li><li>Phar</li><li>SimpleXML</li><li>wddx</li><li>xml</li><li>xmlreader</li><li>xmlwriter</li><li>apache2handler</li><li>gd</li><li>mbstring</li><li>mysql</li><li>mysqli</li><li>pdo_mysql</li><li>pdo_sqlite</li><li>mhash</li><li>xdebug</li>
12-10 15:17:42.975: I/sb.toString()(2589):          </ul>
12-10 15:17:42.975: I/sb.toString()(2589):      </dd>
12-10 15:17:42.975: I/sb.toString()(2589):      <dt>MySQL Version :</dt>
12-10 15:17:42.975: I/sb.toString()(2589):      <dd>5.6.12
12-10 15:17:42.975: I/sb.toString()(2589):  &nbsp;</dd>
12-10 15:17:42.975: I/sb.toString()(2589):  </dl>
12-10 15:17:42.975: I/sb.toString()(2589):  <h2>Tools</h2>
12-10 15:17:42.975: I/sb.toString()(2589):  <ul class="tools">
12-10 15:17:42.975: I/sb.toString()(2589):      <li><a href="?phpinfo=1">phpinfo()</a></li>
12-10 15:17:42.975: I/sb.toString()(2589):      <li><a href="phpmyadmin/">phpmyadmin</a></li>
12-10 15:17:42.975: I/sb.toString()(2589):  </ul>
12-10 15:17:42.975: I/sb.toString()(2589):  <h2>Your Projects</h2>
12-10 15:17:42.975: I/sb.toString()(2589):  <ul class="projects">
12-10 15:17:42.975: I/sb.toString()(2589):  <li><a href="connect_to_db">connect_to_db</a></li><li><a href="phpMyAdmin">phpMyAdmin</a></li><li><a href="travel_buddy">travel_buddy</a></li>
12-10 15:17:42.975: I/sb.toString()(2589):  </ul>
12-10 15:17:42.975: I/sb.toString()(2589):  <h2>Your Aliases</h2>
12-10 15:17:42.975: I/sb.toString()(2589):  <ul class="aliases">
12-10 15:17:42.975: I/sb.toString()(2589):  <li><a href="phpmyadmin/">phpmyadmin</a></li><li><a href="sqlbuddy/">sqlbuddy</a></li><li><a href="webgrind/">webgrind</a></li>         
12-10 15:17:42.975: I/sb.toString()(2589):  </ul>
12-10 15:17:42.975: I/sb.toString()(2589):  <ul id="foot">
12-10 15:17:42.975: I/sb.toString()(2589):      <li><a href="http://www.wampserver.com">WampServer</a></li> - 
12-10 15:17:42.975: I/sb.toString()(2589):         <li><a href="http://www.wampserver.com/en/donations.php">Donate</a></li> -
12-10 15:17:42.975: I/sb.toString()(2589):      <li><a href="http:
public static String url = "URL REMOVED";

如果您删除了URL,那么您将访问localhost,这就是为什么您看到的不是JSON数据,而是Wamp.php信息。

你提到你现在正在托管脚本,那么你必须使用那个URL:

public static String url = "http://www.pathtoyournewscript.com/json.php";

无法帮助您了解具体情况,但如果您希望使用更高级别的库,可以考虑

Jackson它非常快速和干净的

您确定要在正确的位置查找json吗?我通常使用HttpClient并从这样的连接中获取HttpResponse对象。

我相信json将出现在响应体中。

以下是的一个快速示例

http://hc.apache.org/httpclient-3.x/tutorial.html

还有一个

http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientWithResponseHandler.java