解析android中的json时修复类型不匹配错误

时间:2017-03-01 09:42:58

标签: android json

以下是尝试从服务器数据库中搜索

[["30","KAB-097V","726735765","Bus\/Truck\/Lorry","Cash"],["31","KZE-053H","725940835","Bus\/Truck\/Lorry","Cash"],["32","KAG-784K","723489849","Saloon\/pick up\/any other personal car","MPESA"],["33","kab-123p","973934940","Omni Bus\/ Omni Truck","Cash"],["34","KAD-123K","484984745","Omni Bus\/ Omni Truck","Cash"]]

下面是我的java类

 public class Parser extends AsyncTask<Void, Void,Integer> {
    Context c;
    String data;
    RecyclerView rv;
    ArrayList<String> plates = new ArrayList<>();

    public Parser(Context c, String data, RecyclerView rv) {
        this.c = c;
        this.data = data;
        this.rv = rv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        return this.parser();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        if (integer==1){
                rv.setAdapter(new MyAdapter(c,plates));
        }else {
            Toast.makeText(c, "Unable to parse",Toast.LENGTH_SHORT).show();
        }
    }
    private int parser(){
        try {
            JSONArray ja = new JSONArray(data);
            JSONObject jo=null;
            plates.clear();
            for (int i=0; i<ja.length();i++){
                jo =ja.getJSONObject(i);
                String number = jo.getString("payment");
                plates.add(number);
            }
            return 1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

当我运行该类时,它会提供无法解析的上述吐司并提供以下错误

 org.json.JSONException: Value ["27","KAC-123","7585765","Saloon car","MPESA"] at 0 of type org.json.JSONArray cannot be converted to JSONObject    at org.json.JSON.typeMismatch(JSON.java:100)

03-01 04:08:51.166 2929-19534 / com.codek.kipz.parkingverication W / System.err:at org.json.JSONArray.getJSONObject(JSONArray.java:525) 03-01 04:08:51.166 2929-19534 / com.codek.kipz.parkingverication W / System.err:at com.codek.kipz.parkingverication.MySQL.Parser.parser(Parser.java:57)

1 个答案:

答案 0 :(得分:0)

您的示例json不包含任何JSONObjects。相反,它是一个数组数组。

jo =ja.getJSONObject(i);

这里你试着读一个json 对象,但是没有任何东西,所以它会引发异常。

然后你试着读一个名为“支付”的论据。并将它用作一个盘子(它看起来很奇怪)。因为你的json不包含任何命名参数,所以你必须使用它在每个数组中存储的索引。

使用以下代码替换您的解析器方法

private int parser() {
    try {
        JSONArray ja = new JSONArray(data);
        plates.clear();

        for(int i = 0; i < ja.length(); i++) {
            JSONArray array = ja.getJSONArray(i);
            // The plate appears to be stored as the second item in each array
            String plate = array.getString(1);
            plates.add(plate);
        }
        return 1;
    } catch (JSONException e) {
        e.printStackTrace();
        return 0;
    }
}