一尘不染

类型为java.lang.String的Android值…无法转换为JSONArray

json

我的项目有一个WCF,可以从数据库获取记录并以JSON格式返回,如下所示:

{"GetNotesResult":"[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"CreatedBy\":\"thangvc\"},{\"ID\":2,\"Title\":\"Note 2\",\"Content\":\"Hello Nguyen Thi Ngoc\",\"CreatedBy\":\"thangvc\"}]"}

我也有一个Android应用程序来使用JSON,这是我的代码:

private JSONArray getNotes(String UserName, String Password) {
        JSONArray jarray = null;
        JSONObject jobj = null;
        try{
            StringBuilder builder = new StringBuilder(URL);
            builder.append("UserName=" + loggedInUser.getUserName());
            builder.append("&");
            builder.append("Password=" + loggedInUser.getPassword());

            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(builder.toString());
            HttpResponse response = client.execute(httpGet);

            int status = response.getStatusLine().getStatusCode();

            if(status==200)
            {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity,"utf-8");
                jobj = new JSONObject(data);
                jarray = jobj.getJSONArray("GetNotesResult");
            }
            else
            {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        }
        catch(ClientProtocolException e)
        {
            Log.d("ClientProtocol",e.getMessage());
        }
        catch(IOException e)
        {
            Log.d("IOException", e.getMessage());
        }
        catch(JSONException e)
        {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        catch(Exception e)
        {
            Log.d("Unhandle Error", e.getMessage());
        }
        return jarray;
    }

我在处设置了断点,jarray = jobj.getJSONArray("GetNotesResult");并从中得到了以下消息JSONException

Value [{"ID":1,"Title":"Note 1","Content":"Hello Vu Chien Thang","CreatedBy":"thangvc"},{"ID":2,"Title":"Note 2","Content":"Hello Nguyen Thi Ngoc","CreatedBy":"thangvc"}] at GetNotesResult of type java.lang.String cannot be converted to JSONArray

我试图复制JSON字符串并粘贴到在线JSON解析器网站http://jsonviewer.stack.hu/上,它解析得很好。请帮我解决这个问题!


阅读 296

收藏
2020-07-27

共1个答案

一尘不染

在您的json中,的值GetNotesResult包含在其中,""因此将其视为字符串而不是数组。

被解析为一个数组。

{"GetNotesResult":[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"CreatedBy\":\"thangvc\"},{\"ID\":2,\"Title\":\"Note 2\",\"Content\":\"Hello Nguyen Thi Ngoc\",\"CreatedBy\":\"thangvc\"}]}

因此,解决方案是两件事之一:

  1. 如果可以修改服务器响应,请""从json数组周围删除。要么
  2. parse it first as string and then create a json array from that string..
        String notes = jobj.getString("GetNotesResult");
    jarray = new JSONArray(notes);
2020-07-27