java - 将 JSON 对象解析为 Restful Web 服务

标签 java php android json rest

我正在开发一个android注册系统,通过JSON与mysql数据库通信。 Restful Web 服务是用 PHP 和 Slim 库编写的。我已经使用 Advanced Rest Client App 测试了 Web 服务,将 json 有效负载数据解析到其中,并且它工作得非常好,结果如下所示。目前我正在尝试将用户数据从 Android 应用程序解析到服务器,它显示此错误 (Error parsing data org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject) 。我希望有人告诉我我做错了什么,因为我觉得错误来 self 的 JSONParser 类和 Userfunction。提前致谢。

这是我的测试结果

{"tag":"signup","success":1,"error":0,"uid":"547d92b0480711.90973742",
"result":{"firstname":"mish","lastname":"harry","email":"mishael19@gmail.com"}}

这是 JSONParser

public class JSONParser2 {

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

// constructor
public JSONParser2() {
}

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

    try{
        if(method.equals("POST")){
            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();
        }else if(method == "GET"){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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();
    } 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;    
}
}

这是我的用户函数

public class UserFunctions {

private JSONParser2 jsonParser2;

private static String signupURL = "http://globalpadtutorials.globalpad.info/loginSignup/v1/signup";

private static String signup_tag = "signup";

private static String postMethod = "POST";

public UserFunctions(){
    jsonParser2 = new JSONParser2();
}

public JSONObject signupUser(String fname, String lname, String email, String pwd){

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", signup_tag));
    params.add(new BasicNameValuePair("firstname", fname));
    params.add(new BasicNameValuePair("lastname", lname));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", pwd));

    JSONObject json = jsonParser2.makeHttpRequest(signupURL, postMethod, params);
     Log.e("JSON", json.toString());
    return json;
}
}

错误堆栈

12-02 11:04:19.681: E/JSON Parser(10024): Error parsing data org.json.JSONException: Value <html>   
<head><title>Slim of type java.lang.String cannot be converted to JSONObject

PHP 代码

function createUser(){

$request = \Slim\Slim::getInstance()->request();
$resp = \Slim\Slim::getInstance()->response();
$resp['Content-Type'] = 'application/json; charset=utf-8';
$body = $request->getBody();
$users = json_decode($body);
$dbhandler = new DbHandler();
$tag = $users->tag;
$fname = $users->firstname;
$lname = $users->lastname;
$email = $users->email;
$pwd = $users->password;

$response = array("tag" => $tag, "success" => 0, "error" => 0);

if($tag == 'signup') {
    if ($dbhandler->userExisted($email)) {
        $response["error"] = 2;
        $response["error_msg"] = "User already existed";
        echo json_encode($response);
    } else {
        $result = $dbhandler->addUser($fname, $lname, $email, $pwd);
        if ($result != false) {
            $response["success"] = 1;
            var_dump($result);
            $response["uid"] = $result["user_id"];
            $response["result"]["firstname"] = $result["firstname"];
            $response["result"]["lastname"] = $result["lastname"];
            $response["result"]["email"] = $result["email"];
            echo json_encode($response);
        } else {
            $response["error"] = 1;
            $response["error_msg"] = "An error occured during sign up";
            echo json_encode($response);
        }
    }
} else{
    $response["error"] = 1;
    $response["error_msg"] = "Invalid tag request: ".$tag;
    echo json_encode($response);
}
}

html 错误

Slim 应用程序 Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line -height:48px;}strong{display:inline-block;width:65px;}

Slim 应用程序错误

由于以下错误,应用程序无法运行:

详细信息

类型: ErrorException代码: 8消息: 尝试获取非对象的属性文件:/home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php行: 63

跟踪

#0 /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php(63): Slim\Slim::handleErrors(8, 'Trying to get p...', '/home/globa390/...', 63, Array)
12-02 11:55:50.366: E/JSON(27492): #1 [internal function]: createUser()
12-02 11:55:50.366: E/JSON(27492): #2 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Route.php(462): call_user_func_array('createUser', Array)
12-02 11:55:50.366: E/JSON(27492): #3 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Slim.php(1326): Slim\Route->dispatch()
12-02 11:55:50.366: E/JSON(27492): #4 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/Flash.php(85): Slim\Slim->call()
12-02 11:55:50.366: E/JSON(27492): #5 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
12-02 11:55:50.366: E/JSON(27492): #6 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
12-02 11:55:50.366: E/JSON(27492): #7 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Slim.php(1271): Slim\Middleware\PrettyExceptions->call()
12-02 11:55:50.366: E/JSON(27492): #8 /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php(12): Slim\Slim->run()
12-02 11:55:50.366: E/JSON(27492): #9 {main}

最佳答案

 public JSONObject signupUser(String fname, String lname, String email, String pwd){

      List<NameValuePair> params = new ArrayList<NameValuePair>(5);
      params.add(new BasicNameValuePair("tag", signup_tag));
      params.add(new BasicNameValuePair("firstname", fname));
      params.add(new BasicNameValuePair("lastname", lname));
      params.add(new BasicNameValuePair("email", email));
      params.add(new BasicNameValuePair("password", pwd));

      String jsonstr = jsonParser2.makeHttpRequest(signupURL, postMethod, params);
  //cast String into jsonobject
  JSONObject json = new JSONObject(jsonStr);
  return json;

}

关于java - 将 JSON 对象解析为 Restful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248294/

相关文章:

java - 在 Java 中自定义默认的 AbstractColorChooserPanel

php - Laravel BaseController 与\BaseController

php - 如何选择 MySQL 中最常见的值?

java - Maven安装与配置

java - 为什么 Java 和 Perl 中的正则表达式表现不同?

PHP MySQL 比较 $row 从今天开始的日期

Java - Android Mobile Vision人脸检测与轮廓

android - 带有 EditText 的 BottomSheet

Android - 改变 native 线程的优先级?

java - Android 应用程序在重新启动前崩溃