我正在尝试构建一个简单的应用程序,该应用程序能够通过 PHP 界面从在线 mysql 数据库中检索数据。但是,在尝试检索 JSON 并使用 gson 解析为本地 Java 对象时,我不断收到以下错误。我相信它与用于创建数组的 PHP 方法有关,因为这是我第一次涉足 PHP,所以如果有人可以看一下,它会很有帮助。
运行时错误:
10-10 17:51:30.146: W/System.err(683): Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1
返回“工作”数组的 PHP 方法:
public function getAllJobs($email) {
$result = mysql_query("SELECT * from from job WHERE email = '$email'") or die(mysql_error());
$rows = array();
while (($r = mysql_fetch_array($result)) {
$rows[$r['jobId'][$r['desc']] = array(
'techId' => $r['techId'],
'email' => $r['email'],
'dateCreated' => $r['dateCreated'].
'dateClosed' => $r['dateClosed']
);
}
return $rows;
}
调用数据库函数类:
} else if ($tag == 'GetAll') {
$email = $_POST['email'];
$password = $_POST['password'];
$result = array();
$result = $db->getAllJobs($email);
echo json_encode($result);
}
应从 php/sql 查询返回的作业类:
public class Job extends Message{
public Job(MessageType m)
{
this.messageType = m.toString();
}
public String messageType ;
public String jobId;
public String email;
public String techId;
public String desc;
public Date dateCreated;
public Date dateClosed;
@Override
public String getType() {
return messageType;
}
}
最后,来自 CloudConnect 类的 Java 代码:
public synchronized List<Message> getAll(Message m) throws IOException {
List<Message> mList = new ArrayList<Message>();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(site);
post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
if ( status.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
Reader read = new InputStreamReader(is);
mList = Arrays.asList(gson.fromJson(read, Message[].class));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return mList;
}
最佳答案
我真的不懂 PHP,但 Gson 消息对我来说很清楚。 JSON 的第一个字符不是 {
或 [
,这是字符串成为有效 JSON 的必要条件。
因此请检查您的 PHP 代码并验证您的响应是否以 {
开头(因为我怀疑您的代码返回的是单个对象)
对于 JSON Specification :
JSON Grammar
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.
A JSON text is a serialized object or array.
JSON-text = object / array
关于Android 到 PHP 到 MySQL : Expected BEGIN_ARRAY but was STRING at line 1 column 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19302922/