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

953 views Asked by At

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?

3

There are 3 answers

0
Unique Identifier On BEST ANSWER
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.

0
Nikhil G On

Try this -

json_encode($rows, JSON_FORCE_OBJECT);

For more reference, check this link

0
Navneet Krishna On

Try changing your java code like this

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

replace code in your try block with this