JSON错误:java.lang.String无法转换为JSONObject

时间:2015-03-11 16:46:00

标签: php android json gson android-volley

我正在开发一款Android应用,我正在尝试使用 Volley Library 。我无法解决的问题是关于JSON。我检查了我的php文件,结果和Java代码,但我仍然得到同样的错误。

有趣的是, VolleyLog 不会显示错误消息,但是 Log 会显示错误消息。

E/Volley﹕ [1] 2.onErrorResponse: VOLLEY_ERROR

E/LOG﹕ Error: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject

那是我的PHP代码:

<?php
# Inform which carachters type will be used.
header('Content-Type: text/html; charset=utf-8');
 // array for JSON response
$response = array();

// include db connect class

require_once ('../conn.php');
require_once('pClass.php');

error_reporting( E_ALL ); 

// connecting to db
$db = new DB_CONNECT();

//Setting to UTF8
mysql_query("SET NAMES 'utf8_general_ci'");
mysql_query('SET character_set_connection=utf8_general_ci');
mysql_query('SET character_set_client=utf8_general_ci');
mysql_query('SET character_set_results=utf8_general_ci');
mysql_query('SET CHARACTER SET utf8');

    $ff_error = "ERROR";
    $arrPOI["arrPOI"] = array();
    $poi=new POI();

if (isset($_REQUEST["ff_01"])) 
{
    //Execute the query
    $ff_01 = $_REQUEST['ff_01'];
    $return = mysql_query($ff_01) or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($return) > 0) {
        while ($row = mysql_fetch_array($return)) {
            $poi->setPOIId($row["intPointId"]);
            $poi->setPOIName($row["vchPointName"]);
            $poi->setPOIImage($row["vchAwesomeFont"]);
            $poi->setStatusId($row["intStatusId"]);
            $poi->setLanguageId($row["intLanguageId"]);

            // push single category into final response array
            array_push($arrPOI["arrPOI"], $poi->getPOIData());
        }
        // echoing JSON response
        header('Content-Type: application/json');
        echo json_encode($arrPOI, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_NUMERIC_CHECK);
    } else {
        //No data found
        array_push($arrPOI["arrPOI"], $poi->getPOIData());

        // echo no users JSON
        header('Content-Type: application/json');
        echo json_encode($arrPOI);
    }
} else {
    //ERROR
    array_push($arrPOI["arrPOI"], $poi->getPOIData());

    //Echo
    header('Content-Type: application/json');
    echo json_encode($arrPOI);
}   
?>

PHP结果:

{"arrPOI":[{"intPOIId":1,"strPOIName":"Cinema","strPOIImage":"fa-film","intStatusId":1,"intLanguageId":1},{"intPOIId":2,"strPOIName":"Teatro","strPOIImage":"fa-smile-o|fa-frown-o","intStatusId":1,"intLanguageId":1},{"intPOIId":3,"strPOIName":"Restaurante","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":4,"strPOIName":"Bar","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":5,"strPOIName":"Pontos Turísticos","strPOIImage":"fa-map-marker","intStatusId":1,"intLanguageId":1},{"intPOIId":6,"strPOIName":"Cafeteria","strPOIImage":"fa-coffee","intStatusId":1,"intLanguageId":1},{"intPOIId":7,"strPOIName":"Shopping","strPOIImage":"fa-diamond","intStatusId":1,"intLanguageId":1},{"intPOIId":8,"strPOIName":"Livraria","strPOIImage":"fa-book","intStatusId":1,"intLanguageId":1},{"intPOIId":9,"strPOIName":"Show","strPOIImage":"fa-microphone","intStatusId":1,"intLanguageId":1},{"intPOIId":10,"strPOIName":"Boates","strPOIImage":"fa-glass","intStatusId":1,"intLanguageId":1},{"intPOIId":11,"strPOIName":"Lanchonete","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":12,"strPOIName":"Hotéis","strPOIImage":"fa-building","intStatusId":1,"intLanguageId":1},{"intPOIId":13,"strPOIName":"Pub","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":14,"strPOIName":"Pizzaria","strPOIImage":"fa-pie-chart","intStatusId":1,"intLanguageId":1},{"intPOIId":15,"strPOIName":"Univesidade","strPOIImage":"fa-university","intStatusId":1,"intLanguageId":1},{"intPOIId":16,"strPOIName":"Hospital","strPOIImage":"fa-plus-square","intStatusId":1,"intLanguageId":1}]}

我的Java代码:

import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.game.code.guide44.adapter.POIAdapter;
import com.game.code.guide44.app.AppController;
import com.game.code.guide44.data.PointOfInterest;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class POIChoose extends Activity {
    private ListView lVwPOI;
    private POIAdapter adapterPOI;
    private ProgressDialog pDialog;
    private List<PointOfInterest> POIList;
    private String url;
    private StringBuilder stbCheckedPOI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_choose);
        //Initialize with ListView object from  activity_poi_choose by id
        lVwPOI = (ListView)findViewById(R.id.lvwPOI);
        //Initialize the list of POI
        POIList = new ArrayList<PointOfInterest>();
        //initialize with POI List
        adapterPOI = new POIAdapter(this, POIList);
        //Fill the LiistView with POIAdapter content
        lVwPOI.setAdapter(adapterPOI);
        stbCheckedPOI = new StringBuilder();
        //Base url
        //Change "1" to dynamic user language
        url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");

        //Initialize the ProgressDialog
        pDialog = new ProgressDialog(POIChoose.this);
        //Show the progress bar befores making HTTP request
        pDialog.setMessage(getString(R.string.txtMsgPleaseWait));
        pDialog.show();

        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.v("VOLLEY", "Response: " + response.toString());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if(error instanceof NoConnectionError)
                    Toast.makeText(POIChoose.this, "No internet available", Toast.LENGTH_SHORT).show();
                else if(error instanceof ServerError)
                    Toast.makeText(POIChoose.this, "Server Error", Toast.LENGTH_SHORT).show();

                VolleyLog.e("VOLLEY_ERROR", "Error: " + error.getMessage());
                Log.e("LOG", "Error: " + error.getMessage());
                pDialog.dismiss();
            }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    private void parseJsonFeed(JSONObject response){
        try{
            JSONArray jsonArray = response.getJSONArray("arrPOI");
                for (int i = 0; i < response.length(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    PointOfInterest Poi = new PointOfInterest();
                    Poi.setPOIId(jsonObject.getInt("intPointId"));
                    Poi.setPOIName(jsonObject.getString("vchPointName"));
                    Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
                    Poi.setStatusId(jsonObject.getInt("intStatusId"));
                    Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

                    // adding movie to movies array
                    POIList.add(Poi);
                }

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void performSelectPOI(View view){
        for(int i = 0; i < POIList.size(); i++)
        {
            if(adapterPOI.mCheckStates.get(i)==true)
            {
                stbCheckedPOI.append(POIList.get(i).toString());
                stbCheckedPOI.append("\n");
            }
            else
            {

            }
        }
        Toast.makeText(AppController.getContext(), stbCheckedPOI, Toast.LENGTH_LONG).show();
    }
}

我也听说过 GSON 。这是解决方案吗?谁能帮我?在此先感谢!!

1 个答案:

答案 0 :(得分:0)

好吧,我的朋友们,我尝试了一切来解决Java代码中的问题,但我几乎忘了看我的PHP收到了什么。

在我的代码的这一部分:

url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");

我将SQL查询作为参数传递。好吧,PHP没有收到所有查询。例如:如果我通过

"SELECT ID, NAME, ORDER FROM tblOrder"

我的PHP只收到“SELECT”,产生错误(显然是!!)。所以问题不是BOM或UTF-8或类似的东西......是一个基本错误。

所以,解决方案是将SQL查询放在PHP中并只传递几个参数来接收正确答案(在本例中为JSONObject)

非常感谢!!

P.S。:感谢Xjasz!你是对的!!我需要改变这个:

Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

为此:

Poi.setPOIId(jsonObject.getInt("intPOIId"));
Poi.setPOIName(jsonObject.getString("strPOIName"));
Poi.setPOIPicture(jsonObject.getString("strPOIImage"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

谢谢男人!!