2013-10-10 236 views
1

我想构建一个简单的应用程序,它能够通过PHP界面从在线mysql数据库检索数据。但是当我试图检索JSON并使用gson解析本地Java对象时,我仍然收到下面的错误。我相信它与用于创建数组的PHP方法有关,因为这是我第一次进入PHP,所以如果有人能够看一看,这将是有帮助的。运行时Android到PHP到MySQL:预计BEGIN_ARRAY,但STRING在第1行1

错误:

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; 
} 

回答

2

我真的不知道PHP,但GSON消息是很清楚的给我。您的JSON的第一个字符不是{[,这是字符串为有效JSON的必需条件。

因此,检查你的PHP代码并确认你的回应{开始(因为我不知道你的代码将返回一个对象)

对于JSON Specification

  1. JSON语法

    JSON文本是一个令牌序列。这组令牌包括 六个结构字符,字符串,数字和三个字面 名称。

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

    JSON-文本=对象/阵列

+0

你指的是阵列结果吗?或json_encode方法?我更新了代码以反映我认为正确的内容,但我对PHP或Json没有真正的了解。 – fakataha

+0

为了帮助你,只需编辑你的问题与流的内容。如果你不知道该怎么做,请看这里例如:http://stackoverflow.com/a/309718/1360888 – giampaolo

+0

这是最终帮助我解决问题。一些沿着你的建议,但不知道如何在Eclipse中显示输入。 String all = EntityUtils.toString(entity); Log.d(“response”,all);让我看到了PHP抛出的错误,最后是json格式,所以我可以验证它是我想要的。 – fakataha

相关问题