org.json.JSONException:java.lang.String无法转换为JSONArray

时间:2017-07-20 20:56:31

标签: java android json

我在尝试将字符串转换为JSON时遇到以下错误。

  

org.json.JSONException:java.lang.String无法转换为   JSONArray

这是我的Android代码:

public void SendDataToServer(final String name, final String email, final String password){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String QuickName = name ;
                String QuickEmail = email ;
                String QuickPassword = password;


                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
                nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
                nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));


                try {
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpPost httpPost = new HttpPost(Configs.signup);

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data Submit Successfully";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                JSONObject jo = null;


    try {
        //Error occurs on the following line
        JSONArray arr = new JSONArray(result);

        JSONObject jo = arr.getJSONObject(0);
        if (jo.has("status")) {
            //Logic dealing with JSON here
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

这是我的Json结构:

{
    "status": 0,
    "message": "Username already exists"
}

我在第JSONArray arr = new JSONArray(result);

上收到错误

2 个答案:

答案 0 :(得分:0)

您的JSON结构不是JSONArray。它是一个JSON对象。这段代码应该有用。

String result = "{\"status\":0,\"message\":\"Username already exists\"}";

JSONObject jo = null;

  try {
      jo = new JSONObject(result);

      if (jo.has("status")) {
          String status = jo.getString("status");

          if (status.equals("0")) {
              Log.d(TAG, "user name bla bla bla: ");
          } else if (status.equals("1")) {
              Log.d(TAG, "equals 1");
          } else if (status.equals("2")) {
              Log.d(TAG, "equals 2");
          }
      }
  } catch (JSONException e) {
           e.printStackTrace();
  }

答案 1 :(得分:0)

您的代码将使用以下JSON结构,因为它在放入[]

时变为数组

[{     &#34;状态&#34;:0,     &#34; message&#34;:&#34;用户名已存在&#34; }]

但是,通过遍历JSONArray而不是仅访问JSON数组中的第一个JSON对象,可以使代码更加健壮。