用android中的jsonarray解析json对象

时间:2016-07-23 04:25:52

标签: android json

嗨,你好,我是android的新手。我收到服务器的回复。但我得到以下回应..

收到以下错误

Value {"Elec":"Cup1"} at 1 of type java.lang.String cannot be converted to JSONObject

回应如下

{"Electronics":["{\"Elec\":\"Cup0\"}","{\"Elec\":\"Cup1\"}","{\"Elec\":\"Cup2\"}","{\"Elec\":\"Cup3\"}","{\"Elec\":\"Cup4\"}","{\"Elec\":\"Cup5\"}","{\"Elec\":\"Cup6\"}","{\"Elec\":\"Cup7\"}","{\"Elec\":\"Cup8\"}","{\"Elec\":\"Cup9\"}"],"Printable":["{\"Print\":\"Mug0\"}","{\"Print\":\"Mug1\"}","{\"Print\":\"Mug2\"}","{\"Print\":\"Mug3\"}","{\"Print\":\"Mug4\"}","{\"Print\":\"Mug5\"}","{\"Print\":\"Mug6\"}","{\"Print\":\"Mug7\"}","{\"Print\":\"Mug8\"}","{\"Print\":\"Mug9\"}"]}

我发送和接收的回复如下

    class SliderImages extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... urls) {

        return POST1(urls[0]);
    }

    @Override
    public void onPostExecute(String result) {

    }

}

public String POST1(String url) {
    InputStream inputStream;
    String result = "";
    try {
        arraylist = new ArrayList<HashMap<String, String>>();

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();


        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        Log.d("JsonStringSend", json);
        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if (inputStream != null) {
            result = convertInputStreamToString(inputStream);
            Log.d("JSONResponce", result);
            JSONObject jsonObj = new JSONObject(result);
            contacts = jsonObj.getJSONArray("Electronics");
            for (int i = 1; i < contacts.length()-1; i++) {
                JSONObject c = contacts.getJSONObject(i);
                String id = c.getString("Print");
                Log.e("Errrrrrrr",""+id);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    // 11. return result
    return result;
}


private String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;
    inputStream.close();
    return result;

}

所以得到以下错误

Value {"Elec":"Cup1"} at 1 of type java.lang.String cannot be converted to JSONObject

请帮帮我

提前致谢

4 个答案:

答案 0 :(得分:2)

这是在jsoneditoronline.org

中格式化json之后的结果

enter image description here

请注意,'Electronics'数组中的对象不是JSONObject而是String

一个简单的解决方法是先将对象作为String,然后将其解析为JSONObject,如:

    // 10. convert inputstream to string
    if (inputStream != null) {
        result = convertInputStreamToString(inputStream);
        Log.d("JSONResponce", result);
        JSONObject jsonObj = new JSONObject(result);
        contacts = jsonObj.getJSONArray("Electronics");

        // Note contacts.length() NOT contacts.length() - 1
        for (int i = 1; i < contacts.length(); i++) {

            String cString = contacts.getString(i);
            JSONObject c = new JSONObject(cString);

            String id = c.getString("Print");
            Log.e("Errrrrrrr",""+id);
        }
    }

然而,最好的选择是纠正从服务器返回的数据。

答案 1 :(得分:0)

for(int i = 1; i&lt; contacts.length() - 1; i ++)

for(int i = 0; i&lt; contacts.length(); i ++)

答案 2 :(得分:0)

而是调用 getString getJsonObject ,使用 jsonObject.get(key)并检查下面的实例。

Object obj = jsonObject.get(key);
if(obj instanceof String) {
   // retrieve the string
} else if(obj instanceof JsonObject) {
    // retrieve the Json object
}

要从 JsonObject 获取值,请使用 jsonObject.optString .optJsonObject ,而不是 jsonObject.getString 或的 .getJsonObject

答案 3 :(得分:0)

试试这个,

        String response = "{\"Electronics\":[\"{\\\"Elec\\\":\\\"Cup0\\\"}\",\"{\\\"Elec\\\":\\\"Cup1\\\"}\",\"{\\\"Elec\\\":\\\"Cup2\\\"}\",\"{\\\"Elec\\\":\\\"Cup3\\\"}\",\"{\\\"Elec\\\":\\\"Cup4\\\"}\",\"{\\\"Elec\\\":\\\"Cup5\\\"}\",\"{\\\"Elec\\\":\\\"Cup6\\\"}\",\"{\\\"Elec\\\":\\\"Cup7\\\"}\",\"{\\\"Elec\\\":\\\"Cup8\\\"}\",\"{\\\"Elec\\\":\\\"Cup9\\\"}\"],\"Printable\":[\"{\\\"Print\\\":\\\"Mug0\\\"}\",\"{\\\"Print\\\":\\\"Mug1\\\"}\",\"{\\\"Print\\\":\\\"Mug2\\\"}\",\"{\\\"Print\\\":\\\"Mug3\\\"}\",\"{\\\"Print\\\":\\\"Mug4\\\"}\",\"{\\\"Print\\\":\\\"Mug5\\\"}\",\"{\\\"Print\\\":\\\"Mug6\\\"}\",\"{\\\"Print\\\":\\\"Mug7\\\"}\",\"{\\\"Print\\\":\\\"Mug8\\\"}\",\"{\\\"Print\\\":\\\"Mug9\\\"}\"]}";

    try {

        JSONObject jsonObj = new JSONObject(response);
        JSONArray Electronics = jsonObj.getJSONArray("Electronics");
        JSONArray Printable = jsonObj.getJSONArray("Printable");

        for (int i = 1; i < Electronics.length(); i++) {

            String cString = Electronics.getString(i);
            JSONObject c = new JSONObject(cString);
            String Elec = c.getString("Elec");
            Log.e("Elec", "" + Elec);
        }

        for (int i = 1; i < Printable.length(); i++) {

            String cString = Printable.getString(i);
            JSONObject c = new JSONObject(cString);
            String Print = c.getString("Print");
            System.out.println(" Print --> " + Print);
        }
    } catch (Exception e) {

        System.out.println(" time error --> " + e.toString());
    }

logcat的,

  

07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup1   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup2   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup3   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup4   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup5   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup6   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup7   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup8   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc E / Elec:Cup9   07-23 01:48:12.808 8134-8134 / com.example.peacock.abc I / System.out:   打印 - &gt; Mug1 07-23 01:48:12.808 8134-8134 / com.example.peacock.abc   I / System.out:打印 - &gt; Mug2 07-23 01:48:12.808   8134-8134 / com.example.peacock.abc I / System.out:Print - &gt; Mug3 07-23   01:48:12.808 8134-8134 / com.example.peacock.abc I / System.out:Print    - &GT; Mug4 07-23 01:48:12.808 8134-8134 / com.example.peacock.abc I / System.out:Print - &gt; Mug5 07-23 01:48:12.808   8134-8134 / com.example.peacock.abc I / System.out:Print - &gt; Mug6 07-23   01:48:12.808 8134-8134 / com.example.peacock.abc I / System.out:Print    - &GT; Mug7 07-23 01:48:12.808 8134-8134 / com.example.peacock.abc I / System.out:Print - &gt; Mug8 07-23 01:48:12.808   8134-8134 / com.example.peacock.abc I / System.out:Print - &gt; Mug9

我希望你能尽快解决问题....