[英]Java value of type java.lang.string cannot be converted to jsonobject
我有一個API (此處)輸出JSON字符串作為輸出。 我想解析這個JSON。 它剛剛工作,但我可能在我的API或java代碼中改變了一些東西。
這是我正在使用的代碼:
這里, msg
是一個包含api響應的字符串
try {
/* this prints */
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
JSONObject jObject = new JSONObject(msg);
String cleaner_id = jObject.getString("cleaner_id");
/* but this does not */
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
catch(Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
我在php中使用codeigniter框架。
這是我的php模型中的函數:
public function get_cleaner($mobile, $pass){
$this->db->select("cleaner.cleaner_id, cleaner.cleaner_name, cleaner.date_of_joining, cleaner.current_address, cleaner.mobile1, cleaner.mobile2, cleaner.date_of_birth, skill.skill_name as cleaner_designation");
$this->db->from("cleaner");
$this->db->join('skill', 'cleaner.designation = skill.skill_id', 'left');
$this->db->where("mobile1", $mobile);
$this->db->where("user_pass", $pass);
$data = $this->db->get()->result_array();
return $data;
}
這是我的php控制器:
public function getCleaner(){
$mobile_no = $this->input->get('mobile');
$pass = $this->input->get('pass');
if(!is_null($mobile_no) && !is_null($pass))
{
header('Content-Type: application/javascript');
$data = $this->cleaner_model->get_cleaner($mobile_no, $pass);
if(!empty($data))
echo json_encode($data[0]);
else
echo '{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"}';
}
}
我經常搜索並嘗試了很多我在網上找到的不同解決方案,但我嘗試過的解決方案都沒有找到。
更新:
這給出了錯誤
這給出了錯誤
但
這 解析很好,並給我只是鍵未找到異常
Github示例json api和我的api給出了cannot convert string to json obj
異常,但google maps api沒有。 我的api格式有什么問題嗎?
修復:我終於發現我的api輸出有一個隱藏的隱藏字符導致解析錯誤
這是我收到的錯誤的截圖 (太大的截圖,但你明白了......)
我試圖解決這個問題,沒有什么對我有用,我不知道為什么! 我有一個解決方案,但我不知道它是否有意義!
try{
HttpURLConnection conn = (HttpURLConnection) new URL("http://mridulahuja.com/api/index.php/cleaner/getCleaner?mobile=1111111111&pass=njnjhbh").openConnection();
InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
if(line != null){
line = line.substring(line.indexOf("{"));
JSONObject obj = new JSONObject(line);
System.out.println(obj.getString("cleaner_name"));
}
reader.close();
}catch(Exception e){
System.err.println(e.getMessage());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.