1

我正在尝试构建一个简单的应用程序,该应用程序能够通过 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;
}
4

1 回答 1

2

我真的不懂 PHP,但 Gson 的消息对我来说很清楚。JSON 的第一个字符不是{[,这是字符串成为有效 JSON 的必要条件。

因此,请检查您的 PHP 代码并验证您的响应是否以开头{(因为我想知道您的代码返回的是单个对象)

对于JSON 规范

  1. JSON 语法

    JSON 文本是一系列标记。标记集包括六个结构字符、字符串、数字和三个文字名称。

    JSON 文本是一个序列化的对象或数组。

    JSON文本=对象/数组

于 2013-10-10T19:34:44.980 回答