-1

I have an JSON data in format of

[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"test"}]

now I want to fetch those data in my PHP web system. I am sending those data into PHP server from an android application. I am using below code to send it to web server.

public JSONObject sendAndGetJSONfromURL(String url,List<NameValuePair> params){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                httppost.setHeader("Content-type", "application/json");
                httppost.setHeader("Accept", "application/json");
                httppost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
.....

Before send it I print the

jArray.toString()
and got the output as
[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"test"}]

I want to know that how can I fetch those values from PHP system. Can anyone please help me?

Output of the params variable value looks like below before sending via HTTPRequest

[cartdata=[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"},{"username":"UWUDAMITH"}]]
ppreetikaa
  • 1,025
  • 2
  • 14
  • 22
Damith
  • 1,866
  • 3
  • 27
  • 38

4 Answers4

0

Use json_decode()

http://php.net/manual/en/function.json-decode.php

Usage: json_decode($json, true) //decodes json to associative arrays

Muthu Kumaran
  • 16,579
  • 5
  • 43
  • 69
0

http://php.net/manual/en/function.json-decode.php This should come in handy. Also check http://php.net/manual/en/function.json-encode.php for the exact opposite of the function.

Ketchup God
  • 605
  • 5
  • 14
0

When you will send data in urlencoded form, the values will appear in $_POST PHP's array! From where you will be able to decode them using json_decode():

$json = $_POST['json']; // assumes JSON is posted as "json" POST variable
$data = url_decode($json, true); // gets you associative arrays, not objects

The only thing you needto do is to send JSON string as "json" variable in POST, properlu encoded (URL-encoded) in the body of the request.

Tadeck
  • 117,059
  • 25
  • 140
  • 191
  • Am i working on a correct way.Is `httppost.setEntity(new UrlEncodedFormEntity(params));`correct or are there any other was to do it.Any sample code will helpful. – Damith Sep 23 '12 at 07:22
  • It seems web system can not get the JSON from android.But httprequest method is 100% working because i got the response. – Damith Sep 23 '12 at 07:41
  • @Damith: There is no limitation limiting you from getting JSON data sent by Android, when retrieving on the server. The only thing is to send it as urlencoded form. In that part I cannot help you, but I can direct you to the solution: http://stackoverflow.com/q/4330392/548696 – Tadeck Sep 23 '12 at 08:21
  • Thank you for your information.I am still trying to fix the problem. – Damith Sep 23 '12 at 09:00
0

This might not be the best way to do it, as I am new to Java/Android, but it works for me :)

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://www.yourdomain.com/save.php");

      try {
        // Add your data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("id", "1"));
          nameValuePairs.add(new BasicNameValuePair("json",jArray.toString()));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          HttpResponse response = httpclient.execute(httppost);

      } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
      } catch (IOException e) {
          // TODO Auto-generated catch block
      }

This will send a post to the server with a $_POST['id'] = 1 and then $_POST['json'] = to your json data;

Here is save.php. I actually save it to MySQL, so ya.

    <?php
    $server = "localhost";
    $username = "user";
    $password = "pass";
    $database = "db";
    $con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
    mysql_select_db($database, $con);

    $id = $_POST["id"];
    $json = $_POST["json"];

    $sql = "INSERT INTO comments (id, json) ";
    $sql .= "VALUES ($id, '$json')";

    if (!mysql_query($sql, $con)) {
        die('Error: ' . mysql_error());
    } else {
        echo "Comment added";
    }
    mysql_close($con);
    echo json_decode($json);
    ?>
neutron
  • 81
  • 7
  • I followed your code but web system always getting null.What are the chances of happening it.Before send it my `NameValuePair` object value is looks like `[username=test, cartdata=[{"product_id":"33","amount":"1"},{"product_id":"34","amount":"3"},{"product_id":"10","amount":"1"}]]`. – Damith Sep 23 '12 at 08:45
  • @Damith Make sure you add some additional checking to the $_POST vals before you use them, don't want any sql injections. Also, I appologize for posting a MySQL, should use MySQLi. – neutron Sep 23 '12 at 20:29