java.lang.string 无法转换为 JSONArray Android Mysql
Posted
技术标签:
【中文标题】java.lang.string 无法转换为 JSONArray Android Mysql【英文标题】:java.lang.string cannot be converted to JSONArray Android Mysql 【发布时间】:2019-02-16 15:08:50 【问题描述】:我正在尝试为我的图书馆移动应用程序推送今天到期的图书通知,但在我登录后,我的应用程序中弹出此错误。
4:运行 java.lang.string 无法转换为 JSONArray。
我的 php 工作正常,但我该如何解决这个错误?
W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at com.example.ivan.librarymobileapp.backWorkerNotif.doInBackground(backWorkerNotif.java:67)
W/System.err: at com.example.ivan.librarymobileapp.backWorkerNotif.doInBackground(backWorkerNotif.java:23)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:818)
这是我的代码:
backWorkerNotif 类
public class backWorkerNotif extends AsyncTask<String, String, String>
String result = null;
String[] BookTittle;
Context context;
public backWorkerNotif(Context context)this.context = context;
@Override
protected String doInBackground(String... params)
String selectNotif_url = "http://192.168.254.120/LibrayAPI/SelectNotif.php";
String type = params[0];
if (type.equals("Notif"))
String DateNow = params[1];
String BorrowerID = params[2];
try
String data = URLEncoder.encode("date_now", "UTF-8") + "=" +
URLEncoder.encode(DateNow, "UTF-8");
data += "$" + URLEncoder.encode("borrower_id", "UTF-8") + "=" +
URLEncoder.encode(BorrowerID, "UTF-8");
URL url = new URL(selectNotif_url);
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(data);
outputStreamWriter.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
catch (Exception ex)
//Json
try
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject;
BookTittle = new String[jsonArray.length()];
for (int i = 0;i< jsonArray.length();i++)
jsonObject = jsonArray.getJSONObject(i);
BookTittle[i] = jsonObject.getString("BookTittle");
NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_book_black_24dp)
.setContentTitle("Library notification")
.setContentText("Today is the Due Day of"+ BookTittle[i] +"You Borrowed");
NotificationManager notificationManager =(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(0,mbuilder.build())
catch (Exception ex)
ex.printStackTrace();
return null;
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected void onPostExecute(String jsonArray)
super.onPostExecute(jsonArray);
登录课程
public class Login extends AppCompatActivity
EditText username,password;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = findViewById(R.id.edtUsername);
password = findViewById(R.id.edtPassword);
public void onLogin(View view)
String Username = username.getText().toString();
String Password = password.getText().toString();
backWorkerNotif backWorkerNotif = new backWorkerNotif(this);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd");
String DateNow = SF.format(date);
backWorkerNotif.execute("Notif", DateNow, Username);
String Type = "login";
GlobalVariable.BorrowerID = Username;
backgroundWorker _backgroundWorker = new backgroundWorker(this);
_backgroundWorker.execute(Type, Username, Password);
我的 php 代码
<?php
require "Connection.php";
$DateNow = $_POST["date_now"];
$BorrowerID = $_POST["borrower_id"];
$query = "SELECT A.`BookId`,B.`BookTittle`,A.`BorrowerId` FROM `tblborrow` AS A INNER JOIN `tblbooks` AS B ON A.`BookId` = B.`BookId` WHERE `DueDate` = '$DateNow' AND `BorrowerId` = '$BorrowerID'";
$result = mysqli_query($conn,$query);
while($e = mysqli_fetch_assoc($result))
$output[] = $e;
echo json_encode($output);
print (json_encode($output));
?>
我的 PHP 的结果
[
"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11",
"BookId":"9876","BookTittle":"ihi","BorrowerId":"11",
"BookId":"542","BookTittle":"hiragana","BorrowerId":"11",
"BookId":"5421","BookTittle":"wow","BorrowerId":"11"
][
"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11",
"BookId":"9876","BookTittle":"ihi","BorrowerId":"11",
"BookId":"542","BookTittle":"hiragana","BorrowerId":"11",
"BookId":"5421","BookTittle":"wow","BorrowerId":"11"
]
我做错了什么?
【问题讨论】:
发生这种情况是因为您的 php 脚本输出出现问题。尝试运行这个脚本我邮递员。 结果的格式是什么?可以分享一下吗 你应该在'onPostExucute()'中使用那个结果 可能是因为我在我的 php 上使用了 echo 和 print? ["BookId":"101","BookTittle":"计算美元","BorrowerId":"11","BookId":"9876","BookTittle":" ihi","BorrowerId":"11","BookId":"542","BookTittle":"平假名","BorrowerId":"11","BookId":"5421","BookTittle" :"wow","BorrowerId":"11"]["BookId":"101","BookTittle":"计算美元","BorrowerId":"11","BookId":"9876" ,"BookTittle":"ihi","BorrowerId":"11","BookId":"542","BookTittle":"平假名","BorrowerId":"11","BookId":" 5421","BookTittle":"哇","BorrowerId":"11"] 【参考方案1】:正如 Exception 所说,您收到的响应不是 json 格式的 <br
值。
将“application/json”作为请求内容类型的标头。但这并不能保证您的代码将始终有效。通过这样做,您只需要确保您将收到 json 格式的响应。
问题在于输出流的格式。如果您的连接出现任何类型的 HTTP 异常或其他类型的错误,您将不会意识到,因为您吞下了它。用这种方式改变它:
try
String data = URLEncoder.encode("date_now", "UTF-8") + "=" +
URLEncoder.encode(DateNow, "UTF-8");
data += "$" + URLEncoder.encode("borrower_id", "UTF-8") + "=" +
URLEncoder.encode(BorrowerID, "UTF-8");
URL url = new URL(selectNotif_url);
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(data);
outputStreamWriter.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
//JSON
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject;
BookTittle = new String[jsonArray.length()];
for (int i = 0;i< jsonArray.length();i++)
jsonObject = jsonArray.getJSONObject(i);
BookTittle[i] = jsonObject.getString("BookTittle");
NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_book_black_24dp)
.setContentTitle("Library notification")
.setContentText("Today is the Due Day of"+ BookTittle[i] +"You Borrowed");
NotificationManager notificationManager =(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(0,mbuilder.build());
catch (Exception ex)
ex.printStackTrace();
请向我们提供您从 php 收到的示例输出。我的意思是result
值
【讨论】:
我看不出我的代码和你的代码有什么区别 我已将两个 try-catch 块合并为一个块 catch (Exception ex) //Json try 被移除 好的,谢谢。在我的 UrlEncoder 中发现 $ 应该是 & 的问题 先生,我还有一个问题。以上是关于java.lang.string 无法转换为 JSONArray Android Mysql的主要内容,如果未能解决你的问题,请参考以下文章
无法从类型 [java.lang.String] 转换为类型 [java.lang.Long]
ClassCastException:java.lang.Object[] 无法转换为 java.lang.String[] android
不兼容的类型:java.lang.Object 无法转换为 java.lang.String
Android java.lang.Long 无法转换为 java.lang.String