将字符串转换为JSON的问题

时间:2012-08-14 16:21:28

标签: android json

我在javascript中创建这个JSONObject。

    var jsonBack = {id:userID,"dateToday":today, dateYesterday:yesterday,
                   wbsArrayToday:[{wbs:"13232323"}, {wbs:"13232324"}, {wbs:"13232325"}],
                   wbsArrayYesterday:[{wbs:"13232333"}, {wbs:"13232334"}, {wbs:"13232335"}]};

然后我在我的Android应用程序中调用它。

    JSONObject jsonObj = null;
    // Henter response data fra server vha. httpResponse
    HttpEntity entity1 = response.getEntity();
    if (entity1 != null) {
        InputStream is = null;
        try {
            is = entity1.getContent();
            // convert stream to string
            String result = Converter.convertStreamToString(is);

            //Remove []
            //if(result.startsWith("["))
            //  result = result.substring(1, result.length()-1);
            // Create JSON Object
            jsonObj = new JSONObject(result);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            throw new HttpNodeClientException("HttpNodeClientException/IllegalStateException - createResponse():" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new HttpNodeClientException("HttpNodeClientException/IOException - createResponse():" + e.getMessage());
        } catch (JSONException e) {
            e.printStackTrace();
            throw new HttpNodeClientException("HttpNodeClientException/JSONException - createResponse():" + e.getMessage());
        } catch (ConverterException e){
            e.printStackTrace();
            throw new HttpNodeClientException("HttpNodeClientException/ConverterException - createResponse():" + e.getMessage());
        }

我得到一个JSONException。我设计的JSON错了吗?

以下是例外:

08-14 16:14:18.522: I/LoginActivity(418): HttpNodeClientException/JSONException - createResponse
():Value {"id":"11111111","dateToday":"14082012","dateYesterday":"13082012","wbsArrayToday":
[{"wbs":"13232323"},{"wbs":"13232324"},{"wbs":"13232325"}],"wbsArrayYesterday":
[{"wbs":"13232333"},{"wbs":"13232334"},{"wbs":"13232335"}]} of type java.lang.String cannot be 
converted to JSONObject

2 个答案:

答案 0 :(得分:0)

请改用JSONTokener课程。它解析一个字符串并返回一个JSON对象。

答案 1 :(得分:0)

你需要解决的唯一问题就是这一行:

jsonObj = new JSONObject(result);

进入这一个:

jsonObj = new JSONObject(new JSONTokener(result));