当前位置: 首页 > 知识库问答 >
问题:

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

欧奇希
2023-03-14

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

有趣的是,截击日志不显示错误消息,但日志显示错误消息。

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

结果如下:

{"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个答案

应涵容
2023-03-14

我的朋友们,我试着用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)

谢谢!!

附言:谢谢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"));

谢谢你!!

 类似资料:
  • 我正在抛出一个JSON异常,我不知道为什么会抛出它。我已经看了几乎所有和我一样的问题,但我认为我的不同。因此,我从一个网页获得一个JSONArray,它发送的JSON是有效的(我用验证器检查了它)。在JSONArray上执行getJSONObject时引发异常。 这正是它所说的(个人信息被标出): 这是我的Java代码: 错误发生在我去的行: 任何帮助都非常感谢。

  • 我为一个网站做了一个应用程序。它有一个JSON API。im试图获取结果的URL是:

  • 我将客户数据对象存储为共享首选项(Android)中的JSON字符串,并尝试检索转换回客户对象的字符串并用于验证。从对象到JSON字符串的转换非常好,并且存储在首选项中(作为键值(字符串)对)。 当我尝试使用-我总是得到相同的错误值...类型java.lang.字符串不能转换为JSONObject。 我希望一双不同的眼睛能捕捉到我不能捕捉到的东西。带有数据的错误消息(屏蔽): Value 类型为j

  • 我在使用Jaspersoft Studio和Oracle数据库时出错。一旦有一些数据,以下行 引发以下错误: net.sf.jasperreports.engine.java.lang.java.lang.字符串不能转换为java.lang.布尔 我不明白,为什么Jasper Studio会将其转换为布尔值,因为它被定义为字符串: SQL对我来说也很好: 在视图/表格中:

  • 在这里,我试图将数据发送到我的web服务器,并使用解析json并将数据插入mysql数据库。我得到一个错误,表示值stdClass为

  • 我不知道为什么,但是当我试图从JSON获取数据时,我得到了这个错误: JAVA无法在Jsonarray中转换lang.String 这是我的代码, 主要活动: JSON: