1

I have created a php script and pick it up with java but im having trouble converting it to a format that i can use.

php

<?php  
//PDO is a extension which  defines a lightweight, consistent interface for accessing databases in PHP.  
$db=new PDO('mysql:dbname=mydb;host=localhost;','root','');  
//here prepare the query for analyzing, prepared statements use less resources and thus run faster  
$row=$db->prepare('select * from drinks');  

$row->execute();//execute the query  
$json_data=array();//create the array  
foreach($row as $rec)//foreach loop  
{  
$json_array['drinks_id']=$rec['drinks_id'];  
    $json_array['drink_name']=$rec['drink_name'];  
    $json_array['Description']=$rec['Description'];    
//here pushing the values in to an array  
    array_push($json_data,$json_array);  

}  

//built in PHP function to encode the data in to JSON format  
//print_r($json_array);
echo json_encode($json_data,JSON_FORCE_OBJECT);   
?>  

JSON Sample(Each row is accumative instead of being under a certian tag name)

{
   "0":{
      "drinks_id":"1",
      "drink_name":"Uprising Treason West Coast IPA",
      "Description":"Beer"
   },
   "1":{
      "drinks_id":"2",
      "drink_name":"Flying Dog Snake Dog IPA",
      "Description":"Beer"
   },
   "2":{
      "drinks_id":"3",
      "drink_name":"Crafty Dan 13 Guns America IPA",
      "Description":"Beer"
   },
   "3":{
      "drinks_id":"4",
      "drink_name":"Sixpoint Resin Double IPA",
      "Description":"Beer"
   },
   "4":{
      "drinks_id":"5",
      "drink_name":"Sixpoint Bengali IPA",
      "Description":"Beer"
   },
   "5":{
      "drinks_id":"6",
      "drink_name":"ShipYard ",
      "Description":"Beer"
   },
   "6":{
      "drinks_id":"7",
      "drink_name":"Blue Moon Belgian White ",
      "Description":"Beer"
   },
   "7":{
      "drinks_id":"8",
      "drink_name":"BrewDog Punk IPA ",
      "Description":"Beer"
   },
   "8":{
      "drinks_id":"9",
      "drink_name":"Lagunitas IPA",
      "Description":"Beer"
   },
   "9":{
      "drinks_id":"10",
      "drink_name":"Brooklyn Larger ",
      "Description":"Larger"
   },
   "10":{
      "drinks_id":"11",
      "drink_name":"Hazy Hog Cloudy English Cider ",
      "Description":"Cider"
}
}

Method in Android

private void parseJson() {
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpPost httppost = new HttpPost(url);
// Depends on your web service
        httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        Log.i(TAG, "readline : "+reader.readLine());            String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
            Log.i(TAG, "printLine: "+line);
        }
        result = sb.toString();
        JSONObject jObject = new JSONObject(result);
        JSONArray jArray = jObject.getJSONArray("0"); //I BELIVE THIS IS THE ERROR BUT UNCLEAR HOW TO FIX IT
        for (int i=0;i < jArray.length(); i++)
        {
            try {
                JSONObject oneObject = jArray.getJSONObject(i);
                // Pulling items from the array
                int oneObjectsItem = oneObject.getInt("drinks_id");
                String oneObjectsItem2 = oneObject.getString("drink_name");
                String oneObjectsItem3 = oneObject.getString("Description");
                Log.i(TAG, "parseJson: "+oneObjectsItem2);
            } catch (JSONException e) {
                Log.e(TAG, "parseJson1: " +e.getMessage() );
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "parseJson2: "+e.getMessage() );
    }
    finally {
        try{
            if(inputStream != null)
                inputStream.close();}catch(Exception squish){
            Log.e(TAG, "parseJson3: "+squish.getMessage() );
        }
    }
}

Log Cat sample (Only one line is printed?)

E/Menu: parseJson2: Value {"drinks_id":"1","drink_name":"Uprising Treason West Coast IPA","Description":"Beer"} at 0 of type org.json.JSONObject cannot be converted to JSONArray
1
  • 1
    You don't have a JSONArray, you have a JSONObject. If you alter alter your JSON to start and end with [ & ] and you remove the "0", "1" etc, I believe your code should work Commented Feb 1, 2017 at 13:20

1 Answer 1

1

Try this way to creating the associative array in php,

<?php
   $object=array();
   $i=0;
   while($i<10){
     $employee = array("name"=>"hassan", "Designation"=>"Software Engineer");
     $i++;
     $object[]=$employee;
   }
   $orginal["data"]=$object;
   echo json_encode($orginal)
?>

OUTPUT WILL BE

{"data":[{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"}]}
Sign up to request clarification or add additional context in comments.

2 Comments

Tha k you, will have a look when Im in tomorrow
Sounds great. Happy coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.