简体   繁体   English

解析数据时出错 - 字符串无法转换为 JSONObject

[英]Error Parsing Data - String cannot be converted to JSONObject

I want to access Android apps through Web-Service.我想通过 Web-Service 访问 Android 应用程序。 In the web service the new registration is performed.在 Web 服务中执行新的注册。 In the android apps, the xml file for the new registration is made.在 android 应用程序中,新注册的 xml 文件已生成。 The data is saved successfully in SQL server database and it save properly by web service and return data get in jason string.数据成功保存在SQL服务器数据库中,并通过Web服务正确保存并以jason字符串返回数据。 But when string is converted to JSONObject, it give me error like this:但是当字符串转换为 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

I have made activity for registration as RegisterActivity.java我已将活动注册为 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();
                  }
              }
        }
          });

In that the error is occur at the line:因为错误发生在该行:

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

In the JSONParser class, jObj get the null value.在 JSONParser 类中,jObj 获取空值。 The problem is at the line: jObj = new JSONObject(json);问题出在这一行: jObj = new JSONObject(json);
Code of the JSONParser class : 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;

}

} }

Another class of UserFunction in which the service call : public class UserFunction {其中服务调用的另一类 UserFunction : public class 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;

}

}

In response string you are getting jsonArray and not JsonObject, So when you say在响应字符串中,你得到的是 jsonArray 而不是 JsonObject,所以当你说

try {
    jObj = new JSONObject(json);            
}

here json needs to be converted in JsonArray instead JSONObject.这里 json 需要转换成 JsonArray 而不是 JSONObject。 After that get the first object from json array.之后从 json 数组中获取第一个对象。

something like :类似的东西:

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

hope this helps !希望这有帮助!

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

Your Exception explaining you everything你的例外向你解释一切

Your String is JSONArray not JSONObject you need to get JSONObject from JSONArray .你的 String 是JSONArray not JSONObject你需要从JSONArray获取JSONObject

So use JSONArray to get JSONOBbject Change to:所以使用JSONArray来获取JSONOBbject更改为:

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

试试这个...

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

the chances are your web service (apis) is not returning teh data as "json" if apis are written in php - try adding line below如果 apis 是用 php 编写的,那么您的 Web 服务(apis)很可能不会将数据返回为“json” - 尝试在下面添加一行

header('Content-Type: application/json'); header('内容类型:应用程序/json');

and it should work.它应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:解析数据时出错,无法将其转换为JSONObject - Android: Error parsing data and cannot be converted to JSONObject 无法解析JsonObject-错误“无法将字符串转换为JSONObject” - Trouble parsing JsonObject - error 'String cannot be converted to JSONObject' AsyncTask#3解析JSON对象时出错。 字符串不能转换为JSONObject - AsyncTask #3 error parsing JSON object. String cannot be converted to JSONObject 解析数据时出错:JSONException:值 - Error parsing data : JSONException: Value <br of type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:类型java.lang.String无法转换为JSONObject - Error parsing data org.json.JSONException: type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:java.lang.String类型的值 无法转换为JSONObject - Error parsing data org.json.JSONException: Value ���� of type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:值 - Error parsing data org.json.JSONException: Value <!— of type java.lang.String cannot be converted to JSONObject 解析数据时发生错误[java.lang.String类型的值p无法转换为JSONObject - Error parsing data [Value p of type java.lang.String cannot be converted to JSONObject 错误字符串无法转换为JsonObject - Error String cannot be converted to JsonObject 收到错误:解析数据org.json.JSONException时出错:值 - getting error :Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM