我有一个 API (here)输出 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 Controller :
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"}';
}
}
我进行了很多搜索并尝试了在网上找到的很多不同的解决方案,但是我尝试过的解决方案都不适合我。
更新:
this给出错误
this给出错误
但是
this 解析良好并给出了关键未找到异常
Github 示例 json api 和我的 api 给出了 cannot conversion string to json obj
异常,但 google map 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());
}
关于java.lang.string类型的Java值无法转换为jsonobject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701994/