Search code examples
javaphpandroidjsonjsonexception

How to correctly send JSON string from PHP and parse it in Java to get POJO?


I am using json_encode to create JSON string in PHP. $result is my SQL result.

        $final_op="";
        if(empty($result) == false){

            $rows = array();
            while($r = mysqli_fetch_assoc($result)) {
                $rows[] = $r;
            }
            $final_op=json_encode($rows);
        }

when I get this json string at the client end I get it like

 [{"username":"vikasdevde","user_fname":"Vikas Devde","user_work":"Programmer"}]

And I am parsing it in Java as below

                 try{

                        JSONObject jObject = new JSONObject(response);
                        String aJsonUsername = jObject.getString("username");
                        String aJsonFname = jObject.getString("user_fname");
                        String aJsonUserWork = jObject.getString("user_work");

                  }catch(JSONException e){
                        e.printStackTrace();
                        System.out.println("JSON Exception");
                    }

But I'm getting a JSONException, may be it is because of the square brackets around, because after some research I tried with hard-coded string

  "{\"username\":\"vikasdevde\",\"user_fname\":\"Vikas Devde\",\"user_work\":\"Programmer\"}"

and it worked. Could you please let me know what should be the best way to handle this?


Solution

  • JSONArray jsonarray = new JSONArray(response);
    for (int i = 0; i < jsonarray.length(); i++) {
        JSONObject jsonobject = jsonarray.getJSONObject(i);
        String username= jsonobject.getString("username");
        String user_fname= jsonobject.getString("user_fname");
        String user_work= jsonobject.getString("user_work");
    }
    

    That is the right way to go.