Java JSON解析错误。无法将字符串转换为JSONArray
我得到以下错误:Java JSON解析错误。无法将字符串转换为JSONArray,java,php,android,json,parsing,Java,Php,Android,Json,Parsing,我得到以下错误: Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray Parse error on line 1: ^ Expecting '{', '[' 我的JSON代码如下: public String getJsonFromUrl(String url
Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray
Parse error on line 1:
^
Expecting '{', '['
我的JSON代码如下:
public String getJsonFromUrl(String url){
// to initialise the objects
InputStream is = null;
String result = "";
//making HTTP POST request
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
}
// Converting to String
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();
result=sb.toString();
}catch(Exception e){
Log.e(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
}
return result;
}
/**
* To convert the string recieved into json object
* result refers to the string that will be converted
* @return will return the json array
*/
public JSONArray getJarrayFromString(String result){
// Parsing string to JSON Array
try{
jarray = new JSONArray("result"); <---- Error is here
}catch(JSONException e){
Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
}
return jarray;
}
public void onTaskCompleted(String result) {
try {
if(result!=""){
// the remote php link
// converting the response into json array
Log.i(DEBUG, result);
jarray = utils.getJarrayFromString(result);
// number of rows in total for a query
int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
// to check if all the rows are parsed from the mysql
if(from <= mysqlSize){
int rows;
// to check if there is 0
if(jarray.length()>0){
Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
if(from+5<=Math.floor(mysqlSize/nr)*nr){
rows = jarray.length();
}else{
rows = mysqlSize%nr+1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for(int i=1; i<rows; i++){
JSONObject row = jarray.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice") + "£");
bDescription.add(row.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH + row.getString("bImage"));
list.add(row.getString("bImage"));
// to check if an id already exists in the db or to create one if doesn't exist
if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
Log.i(DEBUG, row.getString("bDescription"));
}
new DownloadImages(list, bAdapter).execute();
}
}
postParameters.removeAll(postParameters);
}else{
Utils.IS_ENDED_PRODUCT_LIST = true;
if(rlLoading.isShown()){
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG, "Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
}else{
// if internet connectio is not available
// then, rows will be fetched from the local sqllite database stored on the android phone
if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
我尝试使用(“{result}”)而不是{result)或(“result”),但这会给我带来更多的错误。我很快就能完成整个应用程序,但唯一的问题是将result
字符串转换为有效的JSON数组
如有任何想法和建议,将不胜感激
实现后编辑的日志CAT错误JARRAY=新JSONARRAY(结果)
这一部分
jarray = new JSONArray("result");
当然应该读
jarray = new JSONArray(result);
相反,但我想您已经尝试过了。从解析器错误判断,我假设结果根本不包含有效的JSON字符串。如果它应该表示数组,那么它必须是这样的(以最简单的形式):
对于单引号或双引号,一些JSON解析器很挑剔。但在您的情况下,问题似乎在于括号。请您使用调试器进入getJarrayFromString,检查进入getJarrayFromString的结果值是多少,或者至少可以将原始值打印到控制台?您是否需要在
echo(json_encode
?空格、BOM标记等?jarray=new JSONArray(“结果”);
…为什么是,字符串文本“结果”当然不是JSON数组。您也不会使用!=
来比较java中的字符串
对象。java不是脚本语言。当您尝试直接在浏览器中访问php文件时会发生什么情况?我看到一个额外的}
,这让我怀疑您实际上得到的是错误,而不是JSON输出(或者你删掉了一些代码)@Wrikken在echo语句之前没有任何输出
@BrianRoach我没听清楚。你是说如果我只使用(result),我不应该使用“result”吗,Log Cat显示超过15个错误,包括致命异常和应用程序自动崩溃!!!@datasage,如果我在浏览器中尝试该php,我会得到一个完全空白的白色屏幕!谢谢@alexander.biskop到底需要做什么?我需要在日志输出中添加什么语句?很抱歉,我对这方面还很陌生。美联社我想说的是:你可以添加一个Log.I(…);语句,因为你在代码中的其他地方已经有了它们。然后我意识到在调用getJarrayFromString之前已经有一个Log语句了,上面写着Log.I(DEBUG,result)那么实际上,您应该已经能够看到日志中发生的事情了。就是这样。我只是在日志03-06 21:17:29.417:E/JustDealsUtils(818):在getJarrayFromString()上解析json时出错;org.json.JSONException:java.lang.String类型的值数据库无法转换为JSONArray
如果我使用'jarray=new JSONArray(结果),请参见上面编辑的错误日志Cat;如果图像具有较大的文件大小,是否会出现错误?如上所述,错误可能表明存在一些内存不足错误。每个图像的大小约为14.5KB。您可能无法在日志中看到任何其他内容,因为日志级别设置为错误或其他内容,并且未记录调试信息。目前,请将log.i(DEBUG,result);更改为log.e(调试,结果);以便您可以在日志文件中看到它。
jarray = new JSONArray("result");
jarray = new JSONArray(result);
["abc", "def", "ghi"]