粘贴数据org.json.JSONException时出错

时间:2016-04-07 04:09:53

标签: android mysql json

这是json代码,httpurlconnection从json

获取数据
protected Void doInBackground(Void...params){
        InputStream is=null;

        String result="";

        String urlDate="http://pangkortourism.ga/fyp/player.php";

        BufferedReader reader=null;

        try{

            URL urlp=new URL(urlDate);

            try {
                HttpURLConnection c = (HttpURLConnection) urlp.openConnection();
                c.setRequestMethod("GET");
                c.setReadTimeout(10000);
                c.connect();
                reader = new BufferedReader(new InputStreamReader(c.getInputStream(), "UTF-8"));

                StringBuilder buf = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    buf.append(line);
                }

                result = buf.toString();
            }
            finally {
                if (reader != null) {
                    reader.close();
                }
            }

        } catch (IOException e) {


            Log.e("MalformedURLException", "MalformedURLException " + e.toString());
        }



        //parse json data

        try{

            // Remove unexpected characters that might be added to beginning of the string

                    result=result.substring(result.indexOf("["));

            JSONArray jArray =new JSONArray(result);

            for(int i=0;i<jArray.length();i++){

                JSONObject json_data = jArray.getJSONObject(i);

                Product p=new Product();

                p.setid(json_data.getString("id"));

                p.setitem(json_data.getInt("item"));
                records.add(p);
            }

        }

        catch(Exception e){

            Log.e("ERROR", "Error pasting data "+e.toString());
        }
        return null;

    }

mysql数据库数据

json代码

[
    {"0":"1","id":"1","1":"pizza","item":"pizza"},
    {"0":"2","id":"2","1":"burger","item":"burger"}
]

android studio中的错误

  

04-07 11:58:12.527 23232-23303 / com.khor.newtry6 E /错误:错误粘贴   data org.json.JSONException:类型为item的值pizza   java.lang.String无法转换为int 04-07 11:58:12.542   23232-23232 / com.khor.newtry6 E / size:0

3 个答案:

答案 0 :(得分:0)

“item”字段是String不是整数因此

以下更改:

p.setitem(json_data.getString("item"));

答案 1 :(得分:0)

从代码中删除以下行,因为它会签名以指示json arrya

结果= result.substring(result.indexOf(&#34; [&#34));

然后尝试后可能会有效。 并使用p.setitem(json_data.getInt("item"));

更改项p.setitem(json_data.getString("item"));

答案 2 :(得分:0)

尝试使用p.setitem(json_data.getString(&#34; item&#34;)); INSTEAD OF

p.setitem(json_data.getInt(&#34;项目&#34));

并在方法p.setitem()中更改参数数据类型; to String ..

即。签名为p.setitem();方法应该是:

public void setitem(String item){

this.item = item;

}