【问题标题】:Error Parsing Data - String cannot be converted to JSONObject解析数据时出错 - 字符串无法转换为 JSONObject
【发布时间】:2013-10-04 05:03:13
【问题描述】:

我想通过 Web-Service 访问 Android 应用程序。在 Web 服务中执行新的注册。 在 android 应用程序中,生成了新注册的 xml 文件。数据已成功保存在 SQL Server 数据库中,并通过 Web 服务正确保存,并以 jason 字符串形式返回数据。但是当字符串转换为 JSONObject 时,它会给我这样的错误:

Error parsing data org.json.JSONException: Value [{"userid":105,"created_at":"03-Oct-2013","success":1,"email":"rty@gmail.com","password":"rty12345","name":"rtyu"}] of type org.json.JSONArray cannot be converted to JSONObject

我已将活动注册为 RegisterActivity.java

              else
              {
                  erName.setText("");
                  erPass.setText("");
                  erEmail.setText("");
                  erCopass.setText("");
                  UserFunction userFunction = new UserFunction();
                  JSONObject json = userFunction.registerUser(name, email, password);

                  // check for login response
                  try {
                      if (json.getString(KEY_SUCCESS) != null) {
                          String res = json.getString(KEY_SUCCESS); 
                          if(Integer.parseInt(res) == 1){
                              // user successfully registred
                              // Store user details in SQLite Database
                              Databasehandler db = new Databasehandler(getApplicationContext());
                              JSONObject json_user = json.getJSONObject("user");

                              // Clear all previous data in database
                              userFunction.logoutUser(getApplicationContext());
                              db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),   
                           json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                              // Launch Dashboard Screen
                              Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                              // Close all views before launching Dashboard
                              login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                              startActivity(login);
                              // Close Registration Screen
                              Toast.makeText(RegisterActivity.this,"You are Registered   successfully",Toast.LENGTH_SHORT).show();
                              finish();
                          }else{
                              // Error in registration
                              Toast.makeText(RegisterActivity.this,"User Allready Registered!!!",Toast.LENGTH_LONG).show();
                          }
                      }
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
        }
          });

错误发生在以下行:

  if (json.getString(KEY_SUCCESS) != null)

在 JSONParser 类中,jObj 得到空值。问题出在这条线上:jObj = new JSONObject(json);
JSONParser 类的代码:

 public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

服务调用的另一类 UserFunction : 公共类用户函数 {

 private JSONParser jsonParser;

  // Testing in localhost using wamp or xampp 
 // use http://10.0.2.2/ to connect to your localhost ie http://localhost/
    private static String loginURL = "http://192.168.1.120/rvAndroidServices.ashx";
private static String registerURL = "http://192.168.1.120/rvAndroidServices.ashx";
private static String name1 = "http://192.168.1.120/rvAndroidServices.ashx";

private static String login_tag = "login";
private static String register_tag = "register";
private static String name_tag = "name";

// constructor
public UserFunction(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    jsonParser= new JSONParser();
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    // Log.e("JSON", json.toString());
    return json;
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String name, String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    jsonParser   = new JSONParser();
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}


/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    Databasehandler db = new Databasehandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

public String getAppCategorydetail(Context context){
    Databasehandler db = new Databasehandler(context);
    String count = db.getAppCategorydetail();

        return count;

}
/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    Databasehandler db = new Databasehandler(context);
    db.resetTables();
    return true;
}

public JSONObject chname(String name) 
{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", name_tag));
    params.add(new BasicNameValuePair("name", name));
     JSONObject json = jsonParser.getJSONFromUrl(name1, params);
    return json;

}

}

【问题讨论】:

  • 伙计,首先将成功/失败更改为响应代码,然后将完整的日志粘贴到此处

标签: android json jsonobject


【解决方案1】:

在响应字符串中你得到的是 jsonArray 而不是 JsonObject,所以当你说

try {
    jObj = new JSONObject(json);            
}

这里json需要转换成JsonArray而不是JSONObject。之后从 json 数组中获取第一个对象。

类似:

try {
    JSONArray jArr = new JSONArray(json);  
    JSONObject jObj = jArr.getJSONObject(0);      
}

希望这会有所帮助!

【讨论】:

  • 它给出这样的错误 E/JSON(1415): [{"userid":130,"name":"ruip","password":"ru123456","email":"ru @gma.com","created_at":"04-Oct-2013","success":1}]n 10-04 02:07:37.915: W/System.err(1415): org.json.JSONException: java.lang.Integer 类型的用户 ID 的值 130 无法转换为 JSONObject
  • "userid" 和 "success" 是数字类型。这会造成问题吗?
【解决方案2】:
Error parsing data org.json.JSONException: Value [{"userid":105,"created_at":"03-Oct-2013","success":1,"email":"rty@gmail.com","password":"rty12345","name":"rtyu"}] of type org.json.JSONArray cannot be converted to JSONObject

你的例外解释了一切

您的字符串是JSONArray not JSONObject,您需要从JSONArray 获取JSONObject

所以用JSONArray得到JSONOBbject改成:

jObj  = new JSONArray(json).getJSONObject(0);

【讨论】:

  • 尝试 { jObj = new JSONObject(json);在 json 字符串中获取所有数据,但在 jObj 中,当我尝试从 jason 字符串中获取数据到 jasonObject jObj 中时,jObj 为空。
  • 我试试这个,但它给了我这样的错误:org.json.JSONException: Value 185 at userid of type java.lang.Integer cannot be convert to JSONObject 我该怎么办?
【解决方案3】:

试试这个...

JSONArray data = jsonObj.getJSONArray("data");

【讨论】:

    【解决方案4】:

    您的网络服务 (apis) 可能没有将数据返回为“json” 如果 api 是用 php 编写的 - 尝试在下面添加一行

    header('Content-Type: application/json');

    它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2013-01-10
      • 2013-10-16
      • 2012-12-27
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多