【问题标题】:why does it says it is a string?为什么它说它是一个字符串?
【发布时间】:2015-06-15 19:34:47
【问题描述】:

我是 android 应用程序开发的新手,我需要从本地 xampp mysql 数据库中获取数据。这些是我不断收到的错误消息。

06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:96)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:108)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.StudentJSONParser.parseFeed(StudentJSONParser.java:18)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.MainActivity$ThreadClass.onPostExecute(MainActivity.java:111)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.MainActivity$ThreadClass.onPostExecute(MainActivity.java:95)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:636)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask.access$500(AsyncTask.java:177)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5254)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  

这是我的 php 文件 get_all_products.php

<?php // array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

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

// get all products from products table
$result = mysql_query("SELECT * FROM student") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response = array();

while ($row = mysql_fetch_assoc($result)) {
    // temp user array
    $response[] = $row;
}
// success

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No students found";

// echo no users JSON
header(‘Content-type: application/json’);
echo json_encode($response);
}
?>  

如果我在浏览器上运行 get_all_products.php 的结果,它似乎是正确的......

[{"student_id":"TP028616","student_name":"Shirlyn Hoe Yee Lyn","student_username":"lyn","student_password":"123"},{"student_id":"TP033500","student_name":"Ryan Teh Hoon Meng","student_username":"teh","student_password":"123"}]

这是我的 Android 应用 StudentJSONParser.java 中的 java 类

package com.example.shirlyn.attendancesystem;

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

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

public class StudentJSONParser {
    public static List<Student> parseFeed(String content){

        try {
            System.out.println("begin parsing");
            JSONArray ar = new JSONArray(content);
            List<Student> studentList = new ArrayList<>();

            for(int i = 0 ; i < ar.length() ; i++){
                System.out.println("loop " + i);
                JSONObject obj = ar.getJSONObject(i);
                Student student = new Student(obj.getString("student_id"), obj.getString("student_name"), obj.getString("student_username"), obj.getString("student_password"));

                studentList.add(student);
                System.out.println("complete loop " + i);
            }
            System.out.println("complete parsing");

            return studentList;

        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("error parsing");

            return null;
        }

    }
}

这是 .php 文件没有返回 jsonarrays 的问题吗?或者我的应用程序的逻辑是错误的?提前感谢所有回复。

这是我的异步任务类

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Button loginbtn;
private EditText usernameTxt, passwordTxt;
private ProgressBar pb;

private List<Student> studentslist;

public final static String readStudentphp = "http://192.168.0.103/webservice/get_all_products.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    OnClickButtonListener();
    initLogin();
    pb = (ProgressBar) findViewById(R.id.progressBar);
    pb.setVisibility(View.INVISIBLE);
}

private void initLogin(){
    usernameTxt = (EditText) findViewById(R.id.usernameTxt);
    passwordTxt = (EditText) findViewById(R.id.passwordTxt);
}

private void OnClickButtonListener(){
    loginbtn = (Button) findViewById(R.id.login);
    loginbtn.setOnClickListener(this);
}

private void requestData(String uri){
    ThreadClass t = new ThreadClass();
    t.execute(uri);
}

@Override
public void onClick(View v) {
    requestData(readStudentphp);
    //Intent intent = new Intent("com.example.shirlyn.attendancesystem.MainMenu");
    //startActivity(intent);
}

@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_main, 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);
}

private class ThreadClass extends AsyncTask<String, String, String>{
    @Override
    protected void onPreExecute(){
        pb.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        String content = HTTPManager.getData(params[0]);

        return content;
    }

    @Override
    protected void onPostExecute(String result){
        System.out.println("Before parsing");
        studentslist = StudentJSONParser.parseFeed(result);
        System.out.println("After parsing");
        if(studentslist != null && studentslist.size() > 0)
            System.out.println(studentslist.get(0).getStudent_name());
        pb.setVisibility(View.INVISIBLE);
    }
}

}

【问题讨论】:

  • 刚刚离开你的标题我猜你可能需要在发送 JSON 时发送适当的标题....'application/json' 确切的错误是什么?
  • 当有结果时你缺少header(‘Content-type: application/json’);,我建议使用一个简单的响应类来解决这个问题。
  • 这是一个错误,我在我的 php 文件中删除了它。谢谢指出

标签: java php android mysql json


【解决方案1】:

看起来您正在尝试将 HTML 解析为 JSON(基于错误中的 &lt;br 标记)。

&lt;br of type java.lang.String cannot be converted to JSONArray

仔细检查您尝试解析的输出,以确保您从端点返回 JSON。可能是一个接受头或类似的东西。

【讨论】:

  • 所以我的 php 文件没有问题吗?从 json 数组中,我想将它们保存在数组中。
  • @user3244616 如果上述答案解决了您的问题,您可以接受答案。我的 php 文件没有问题是什么意思?
  • 尚不清楚您是否正在使用您打算执行的 PHP 代码。如果您查看您尝试解析为 JSON 的整个字符串,您应该能够找出返回该 HTML 的内容。我看到的 PHP 代码似乎没有返回 HTML,所以你没有点击它或者收到@MarcB 建议的错误是有道理的。
  • 您的 php 文件有 SOMETHING 错误,它正在输出 html。通常这意味着你有一个 PHP 警告/错误,其中将包含 html。
  • [{"student_id":"TP028616","student_name":"Shirlyn Hoe Yee Lyn","student_username":"lyn","student_password":"123"},{"student_id" :"TP033500","student_name":"Ryan Teh Hoon Meng","student_username":"teh","student_password":"123"}] 这是我从传递给parseFeed(字符串内容)
猜你喜欢
  • 2020-08-16
  • 2020-05-03
  • 1970-01-01
  • 2013-05-28
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多