简体   繁体   English

将JSON对象解析为Restful Web服务

[英]Parsing JSON Object to Restful web service

I am developing an android registration system that communicates with a mysql database through JSON. 我正在开发一个通过JSON与mysql数据库通信的android注册系统。 The restful web service was written with PHP and Slim library. 宁静的Web服务是用PHP和Slim库编写的。 i have tested the web service using Advanced Rest Client App by parsing a json payload data into it and it works perfectly fine with the result shown below. 我已经通过将JSON有效负载数据解析为其中的内容,使用Advanced Rest Client App测试了Web服务,它的工作效果非常好,如下所示。 At the moment i am trying to parse user data from the android app to the server and it shows this error (Error parsing data org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject) . 目前,我正在尝试将用户数据从android应用解析到服务器,并且显示此错误(Error parsing data org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject) I would someone to tell me what i am doing wrong coz i feel the error is from my JSONParser class and Userfunction . 我会告诉我我在做错什么,因为我觉得错误来自我的JSONParser类和Userfunction Thanks in advance. 提前致谢。

Here is my test result 这是我的测试结果

{"tag":"signup","success":1,"error":0,"uid":"547d92b0480711.90973742", { “标记”: “注册”, “成功”:1, “错误”:0, “UID”: “547d92b0480711.90973742”,
"result":{"firstname":"mish","lastname":"harry","email":"mishael19@gmail.com"}} “结果”:{ “名字”: “米什”, “姓氏”: “哈里”, “电子邮件”: “mishael19@gmail.com”}}

Here is JSONParser 这是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;    
}
}

here is my Userfunction 这是我的用户功能

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;
}
}

Error stack 错误堆栈

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 code 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 error html错误

Slim Application 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 Application 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: 48像素;} {强显示:内联块;宽度:65px;}

Slim Application Error 苗条的应用程序错误

The application could not run because of the following error: 由于出现以下错误,该应用程序无法运行:

Details 细节

Type: ErrorException Code: 8 Message: Trying to get property of non-object File: /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php Line: 63 类型: ErrorException 代码: 8 消息:试图获取非对象文件的属性 /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php 行: 63

Trace 跟踪

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

} }

Your url returns html page with 404 error. 您的网址返回带有404错误的html页面。 That's why you cant parse it as json. 这就是为什么您不能将其解析为json的原因。

I also had the same issue. 我也有同样的问题。 Ask your Server admin for the permissions for using the database for both web and mobile. 向您的服务器管理员询问使用该数据库用于Web和移动设备的权限。 After that paste your php files in public_html. 之后,将您的php文件粘贴到public_html中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM