淺談thinkphp中將字符串轉換成json數組的方法


這是一部分代碼:
$client = M("Client");
$data = $client->where('user_id ='.$user_id)->select();
if($data == false || $data == null)
{
/*查詢錯誤*/
$str = array(
'status' => 'error',
'msg' => '查詢錯誤',
'content'=> 'null'
);
$this->ajaxReturn($str);

}
else
{
/*查詢成功*/
$str = array(
'status' => 'success',
'msg' => '查詢成功',
'content'=> $data
);
$this->ajaxReturn($str);
}
 
注意一下:php比較兩個字符串盡量不要用 == 來比較,會出現意料不到的后果;盡量用strcmp來比較,當結果為0 的時候表示想等。
 
這是兩種結果:
 
1、存在用戶的:
 
{"status":"success","msg":"\u67e5\u8be2\u6210\u529f","content":[{"client_id":"000003","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"},{"client_id":"000002","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"},{"client_id":"000001","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"},{"client_id":"000000","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"},{"client_id":"000004","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"},{"client_id":"000005","client_name":"\u5f90\u5229\u5175","client_phone":"18813752547","client_address":"\u5e7f\u4e1c\u97f6\u5173\u7fc1\u6e90","client_picture":"http:\/\/www.baidu.com","user_id":"18813752547"}]}
 
2、不存在用戶的:
 
{"status":"error","msg":"\u67e5\u8be2\u9519\u8bef","content":"null"}
 
 
相信大家都很關心一個問題:就是在android客戶端如何解析這種json格式?我來為大家解答一下:
假設實現了android客戶端將從服務器讀取過來的內容保存在buider里面,則接下來:
JSONObject jsonobject1 = new JSONObject(builder.tostring()).getJSONObject(“status”);
JSONObject jsonobject2 = new JSONObject(builder.tostring()).getJSONObject(“msg”);
JSONObject jsonobject3 = new JSONObject(builder.tostring()).getJSONObject(“content”);
String client_id = jsonobject3.getString(“client_id”);
String client_name = jsonobject3.getString(“client_name”);
…………
一次類推。
至於其他格式的json解析,自行網上查找方法。
可以參考一下這個:http://www.cnblogs.com/cpcpc/archive/2011/07/22/2122989.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM