0

I am developing an app with Kotlin-PHP-MySql.

I will be appreciated if someone has an idea why I get this exception "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path" when I call createUser function.

I don't get an exception when I call getUser function with Same api.

I checked these two functions in postman. JSONs are formatted properly. Begins with { "key" : "value", "key1" : "value1", .... }

This is my api:

     interface Api {
     ...
     @POST("/api/v1/users/register_user.php")
     suspend fun createUser(
         @Body userDto: UserInfoPreviewDto
     ) : QueryResponse

     @POST("/api/v1/users/get_user.php")
     suspend fun getUser(
         @Body  jsonObject : JsonObject
     ) : UserDto
    }

and my Retrofit instance:

    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(RamonApiUser::class.java)

and my server-side php code is register_user.php file:

      header("Access-Control-Allow-Origin: *");
      header("Content-Type: application/json; charset=UTF-8");
      header("Access-Control-Allow-Methods: POST");
      header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow- 
            Headers, Authorization, X-Requested-With");
      include_once("../../config/database.php");
      include_once("../../classes/user.php");
      $db = new Database();
      $connection = $db->connect();
      $user = new User($connection);
      if($_SERVER['REQUEST_METHOD'] === "POST") {
        $data = json_decode(file_get_contents("php://input"));
        $user->username =  $data->username;
        $user->password =  $data->password;
        $user->fullname =  $data->fullname;
        $user->email =  $data->email;
        if($user->register()) {
            http_response_code(200);
            $result = array( 
                "status" => "200", 
                "message" => "saved"
            );
            echo json_encode($result);
         }
         else {
            http_response_code(500);
            echo json_encode(array(
                "status" => "500",
                "message" => "Error 500"   
            ));
        }    
      }
      else {
          http_response_code(503);
          echo json_encode(array(
                                 "status" => "503",
                                 "message" => "Error 503"   
                           ));
      }

this my get_user.php file:

    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, 
             Authorization, X-Requested-With");
    include_once("../../config/database.php");
    include_once("../../classes/user.php");
    $db = new Database();
    $connection = $db->connect();
    $user = new User($connection);  
    if($_SERVER['REQUEST_METHOD'] === "POST") {
        $param = json_decode(file_get_contents("php://input"));
        if(!empty($param->id)) {
            $user->id = $param->id;
            $user_data = $user->getById();
            if (!empty($user_data)) {
                http_response_code(200);
                $user_data['isPublicProfile'] = (bool)$user_data['isPublicProfile']; 
                $user_data['isLastOnlineVisible'] = 
                                     (bool)$user_data['isLastOnlineVisible'];
                $user_data['isPhoneNumberVisible'] = 
                                     (bool)$user_data['isPhoneNumberVisible'];
                echo json_encode($user_data);
            }
        } 
     }
     else {
          http_response_code(503);
          echo json_encode(array(
                     "status" => "0",
                     "message" => "503 error"   
       ));
     }

getById() function in user.php :

    public function getById() {
        $sqlQuery = "SELECT * FROM ". $this->table_name ." WHERE id = ? LIMIT 0,1";
        $obj = $this->conn->prepare($sqlQuery);
        $obj->bind_param("i", $this->id);
        $obj->execute();
        $data = $obj->get_result();
        return $data->fetch_assoc();
    }

I have QueryResponse data class in the client-side with the fields status and message. user->register() returns true or false . I think the problem is with my json_encode method. I also tried this: I created a QueryReponse php class with fields status and message and encode this object like this:

    $query_response = new QueryResponse();
    $query_response->status = "200";
    $query_response->message = "registration successful";
    $echo json_encode($query_response);

it didn't help either.

5

1 Answer 1

0

I created another file called get_query_response.php. Just to make sure that my QueryResponse classes are OK and doesn't throw exceptions.

get_query_response.php:

     ....
     include_once("../../config/database.php");
     include_once("../../classes/query_response.php");
     $db = new Database();
     $connection = $db->connect();
     $query_response = new QueryResponse($connection);
     if($_SERVER['REQUEST_METHOD'] === "POST") {
            $query_response->id = 1;
            $query_response_data = $query_response->getById();
            // I fetch query_response_data from mysql
            if (!empty($query_response_data)) {
                http_response_code(200);
                $result = array(
                    "status" => "500",
                    "message" => "save successfully"
                );
                echo json_encode($result); // doesn't throw exception. 
                                               works fine
                //echo json_encode($query_response_data); 
                //when i use this line, it doesn't throw exception 
                //either. works fine
            }       
      }

I call this file get_query_response.php from my api like this:

    interface MyApi {
    ...
    @POST("/api/v1/users/get_query_response.php")
    suspend fun getQueryResponse() : QueryResponse
    ...
    }

No errors, no exceptions. Both echo json_encode($result) and echo json_encode($query_response_data) works fine. The only difference between two register_user.php and get_query_response.php files is this line:

    $data = json_decode(file_get_contents("php://input"));

I don't get the reason why these two files behave differently. They are almost identical. Why does not this code work in register_user.php?

            $result = array(
                "status" => "200",
                "message" => "saved successfully"
            );
            echo json_encode($result);

I finally solved the problem. It was my data class UserInfo. One field of the class was being assigned null during instantiation. Api is sending a class which two properties of that class has null values. The problem is solved by assigning values to those properties.

1
  • 1
    Hi, @rahman. Your answer doesn't look like an actual answer. It looks more like the continuation of the question itself. Might be good to rewrite it if you're able to fix the issue.
    – rjmAmaro
    Commented Feb 23, 2022 at 23:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.