简体   繁体   English

如何从PHP返回JSON对象以从Android应用程序中读取

[英]How to return JSON Object from PHP to read from Android App

I have the following MySQL table. 我有以下MySQL表。

在此输入图像描述

I need to send the dealer name from android app and send all matching rows to the app.I dont know how to set the php output.I know i should encode using json_encode(array('stuff')); 我需要从android应用程序发送经销商名称并将所有匹配的行发送到app.I不知道如何设置php输出。我知道我应该使用json_encode(array('stuff'));进行编码json_encode(array('stuff'));

But i dont know how to format the data.Been checking http://www.w3schools.com/json/ It shows an example 但我不知道如何格式化数据.Been检查http://www.w3schools.com/json/它显示了一个例子

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

Should i use the same format?How to read this from android ?Im referring http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php 我应该使用相同的格式吗?如何从android读取?我指的是http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php

EDIT: 编辑:

    <?php

  //$con goes here 
    $result=$conn->query("SELECT pname FROM products");
    $response["stuff"] = array();

        while($row = $result->fetch_assoc())    {

            $stuff= array();

            /* ADD THE TABLE COLUMNS TO THE JSON OBJECT CONTENTS */
            $stuff["pname"] = $row['pname'];
            array_push($response["stuff"], $stuff);

            // $response[] = $row;
        }
        // success
        $response["success"] = 1;
        echo(json_encode($response));


    /* CLOSE THE CONNECTION */
    mysqli_close($conn );
    ?>

JAVA Code: JAVA代码:

package com.example.testing;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

class testing extends AsyncTask<Void, Void, Void>   {
    JSONParser jParser; 
    String URL_TO_PHP = "http://coolsite.com/dashboard/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    protected Void doInBackground(Void... args) {

        /* Building Parameters */
        List <NameValuePair> params = new ArrayList<NameValuePair>();

        /* getting JSON string from URL */
        JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

        try {
            /* Checking for SUCCESS TAG */
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                /** CHECK THE NUMBER OF RECORDS **/
                int intStuff = JAStuff.length();

                if (intStuff != 0)  {

                    for (int i = 0; i < JAStuff.length(); i++) {
                        JSONObject JOStuff = JAStuff.getJSONObject(i);
                        Log.e("ALL THE STUFF", JOStuff.toString());

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
} 

Main activity 主要活动

package com.example.testing;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);

    }
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
          new testing().execute();
            break;
        default:
            break;
        }

    }


}

Manifest 表现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

JSON Response in PHP PHP中的JSON响应

{"stuff":[{"pname":"Advocates"},{"pname":"Notaries"},{"pname":"Agriculture \/ Fertilizer"},{"pname":"Airconditioners"},{"pname":"Animation"},{"pname":"Airline Companies"},{"pname":"Aluminium Fabricators"},{"pname":"Amusement Parks"},{"pname":"Pets shop"},{"pname":"Association \/ Societies"},{"pname":"Astrology"},{"pname":"Attestation Service"},{"pname":"Auditorium"},{"pname":"Automobiles Accessories"},{"pname":"Automobile Dealers"},{"pname":"Ayurveda"},{"pname":"Gifts Articles"},{"pname":"Bags"},{"pname":"Batteries"},{"pname":"Bearings"},{"pname":"Beauty Parlours \/ Spa"},{"pname":"Magazine Dealers"},{"pname":"Building Contractors"},{"pname":"Building Materials"},{"pname":"Cameras"},{"pname":"Cast Iron Products"},{"pname":"Home Delivery"},{"pname":"Cements Wholesale \/ Retail"},{"pname":"Chemicals"},{"pname":"Contractors"},{"pname":"Consultants"},{"pname":"Parcel Services"},{"pname":"Crockery"},{"pname":"Dental Clinics"},{"pname":"Cyber Parks"},{"pname":"Dance School\/Costumes"},{"pname":"Diagnostics Labs& X-Rays"},{"pname":"Distance Education"},{"pname":"Driving Schools"},{"pname":"Dry Cleaners"},{"pname":"DTH Services"},{"pname":"DTP Centers"},{"pname":"Electrical Contractors \/ Services"},{"pname":"Electronics Equipment \/ Servicing"},{"pname":"Coaching Centre"},{"pname":"Event Management"},{"pname":"Fancy \/ Stationery"},{"pname":"Pooja stores"},{"pname":"Food Products"},{"pname":"Foot Wear"},{"pname":"Foreign Exchange"},{"pname":"Furniture shop"},{"pname":"Granites \/ Marbles"},{"pname":"Hospitals \/ Clinics"},{"pname":"Computer Accessories"},{"pname":"Kitchen Cabinets"},{"pname":"Library"},{"pname":"Lights \/ Fittings"},{"pname":"Mobile Phone Accesseries"},{"pname":"Machinery \/ Tools"},{"pname":"Timber Manufacturer"},{"pname":"Real Estate Agents"},{"pname":"Security Services"},{"pname":"Solar Products"},{"pname":"Health & Fitness"},{"pname":"Travel Agencies"},{"pname":"Used Car \/ Bikes"},{"pname":"Waste Management"},{"pname":"Watches & Clocks"},{"pname":"Handicrafts"},{"pname":"Doors & Windows"}],"success":1}

Since you post does not mention a working PHP file, I will include it for the sake of completeness. 由于你的帖子没有提到一个有效的PHP文件,我会为了完整性而包含它。 This could be a long ( long ) post.... 这可能是一个长( )的帖子....

So, first. 所以,首先。 This is an example of a PHP file that is stored with the name my_test.php in at this location: c:\\wamp\\www\\some_folder_name\\my_test.php ( Please see the edit history for the code ) 这是一个PHP文件的示例,该文件在此位置以名称my_test.php存储: c:\\wamp\\www\\some_folder_name\\my_test.php请参阅代码的编辑历史记录

Now, let me explain the important portions of this PHP. 现在,让我解释一下这个PHP的重要部分。 These parameters should be configured to use your settings: 应将这些参数配置为使用您的设置:

$DB_HOST = 'YOUR_IP_ADDRESS';
$DB_UNAME = 'MYSQL_USERNAME';
$DB_PWD = 'MYSQL_USER'S_PASSWORD';
$DB_DATABASE = 'DATABASE_NAME';

The IP Address should be either localhost or the IP address of the computer hosting the MySQL database. IP地址应该是localhost或托管MySQL数据库的计算机的IP地址。 Preferably an IP address so you can test on physical devices. 最好是IP地址,以便在物理设备上进行测试。 using localhost would work only on Virtual Devices. 使用localhost仅适用于虚拟设备。

Next up is adding the columns to an array that will construct a single record ( row ) in the JSON response. 接下来是将列添加到将在JSON响应中构造单个记录( )的数组中。 Take a look at this line for example: 看一下这一行,例如:

$stuff["id"] = $row['id'];

The $stuff["id"] will basically become the tag in the resulting JSON Object whereas the $row['id'] is what indicates the column name from your DB's table. $stuff["id"]基本上将成为生成的JSON对象中的标记 ,而$row['id']表示数据库表中的列名。 So the $row["...."] has to be identical to the column names in the DB table. 所以$row["...."]必须与DB表中的列名相同。 While the $stuff["...."] can be just about anything. 虽然$stuff["...."]可以是任何东西。 As long as it makes sense to you. 只要它对你有意义。

This line echo(json_encode($response)); 这行echo(json_encode($response)); will convert the response into a JSON format. 转换响应成JSON格式。

Now lets look at the Java code. 现在让我们看一下Java代码。 First up in this is a class that will help you parse through the result. 首先,这是一个可以帮助您解析结果的类。 It was taken off a tutorial off a website ( I don't remember which ). 它取消了一个网站的教程( 我不记得哪个 )。 Just copy an paste the following code in a Java class. 只需将以下代码粘贴到Java类中即可。 No need to change anything in this file. 无需更改此文件中的任何内容。 Do give it a good read to understand how it works. 请仔细阅读以了解其工作原理。 I have it named JSONParser ( Please see the edit history for the code ): 我把它命名为JSONParser请参阅代码的编辑历史记录 ):

Finally, how would to actually get the resulting JSON and parse it in an Activity / Fragment . 最后,如何实际获取生成的JSON并将其解析为Activity / Fragment

I parse the data in an AsyncTask , which is required anyway considering you will be performing a network operation. 我在AsyncTask解析数据,无论如何,考虑到您将执行网络操作,这是必需的。 ( Please see the edit history for the code ) 请参阅代码的编辑历史记录

Points to note in this Java: Java中的注意事项:

  1. This String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php"; String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php"; needs to have either an IP address such as 192.168.0.x or if you are testing on a virtual device, it should be 10.0.2.2 . 需要有一个IP地址,如192.168.0.x,或者如果你在虚拟设备上测试,它应该是10.0.2.2 The earlier ( 192.. ) won't work on an emulator and the later ( 10.0... ) won't work on a physical device. 较早的( 192 .. )将无法在模拟器上运行,而后者( 10.0 ... )将无法在物理设备上运行。
  2. In this: String TAG_STUFF = "stuff"; 在这: String TAG_STUFF = "stuff"; , the "stuff" corresponds with this from the PHP file: $response["stuff"] = array(); "stuff"与PHP文件对应: $response["stuff"] = array(); . The TAG_STUFF should basically use whats in $response["stuff"] . TAG_STUFF基本上应该在$response["stuff"]使用什么。

Hope all the above makes sense. 希望以上所有都有道理。 Comment if you need help. 如果您需要帮助,请评论。 ;-) ;-)

UPDATED WITH WORKING SOLUTION: 更新工作解决方案:

This is very weird indeed. 这确实非常奇怪。 But, I have a working solution. 但是,我有一个有效的解决方案。 When using the OP's code, the application indeed crashes. 使用OP的代码时,应用程序确实崩溃了。 For lack of time to test why it crashes, I am instead posting a solution directly. 由于没有时间来测试它崩溃的原因,我直接发布了一个解决方案。

First, instead of keeping testing as an independent class, create it as an inner class back in the MainActivity . 首先,不要将testing保持为独立类,而是将其创建为MainActivity的内部类。

class testing extends AsyncTask<Void, Void, Void>   {
....
}

Second, declare the variables globally ( the jParser , URL_TO_PHP , etc ), as against the current declarations before the onPreExecute() . 其次,全局声明变量( jParserURL_TO_PHP ),与onPreExecute()之前的当前声明onPreExecute() See the complete solution below for clarity... 请参阅下面的完整解决方案以明确...

public class MainActivity extends Activity {

    JSONParser jParser;
    String URL_TO_PHP = "http://testbox.site50.net/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    ....

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                new testing().execute();
                break;
            default:
                break;
        }

    }

    private class testing extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... args) {

            /* Building Parameters */
            List<NameValuePair> params = new ArrayList<>();

            /* getting JSON string from URL */
            JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

            try {
                /* Checking for SUCCESS TAG */
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                    /** CHECK THE NUMBER OF RECORDS **/
                    int intStuff = JAStuff.length();

                    if (intStuff != 0) {

                        for (int i = 0; i < JAStuff.length(); i++) {
                            JSONObject JOStuff = JAStuff.getJSONObject(i);
                            Log.e("ALL THE STUFF", JOStuff.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
}

While testing, I also took a screengrab of the results. 在测试时,我还拍了一些结果。 Here it is: 这里是: 在此输入图像描述

Again, because I am stretched a little thin at the moment, I won't be able to go find out what really is causing the crash in the OP's code. 再一次,因为我现在感到有点瘦,我将无法找出导致OP代码崩溃的真正原因。 But it's intriguing enough to find out.. 但它很有趣,很容易找到..

This is an example how to use Volley.jar (lib) to parse your JSON. 这是一个如何使用Volley.jar(lib)来解析JSON的示例。

private void makeJsonArrayRequest() {

showpDialog();

JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                try {
                    // Parsing json array response
                    // loop through each json object
                    jsonResponse = "";
                    for (int i = 0; i < response.length(); i++) {

                        JSONObject person = (JSONObject) response
                                .get(i);

                        String name = person.getString("name");
                        String email = person.getString("email");
                        JSONObject phone = person
                                .getJSONObject("phone");
                        String home = phone.getString("home");
                        String mobile = phone.getString("mobile");

                        jsonResponse += "Name: " + name + "\n\n";
                        jsonResponse += "Email: " + email + "\n\n";
                        jsonResponse += "Home: " + home + "\n\n";
                        jsonResponse += "Mobile: " + mobile + "\n\n\n";

                    }

                    txtResponse.setText(jsonResponse);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }

                hidepDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();
            }
        });

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);

} }

from : link 来自: 链接

You have to use JSONParser class.It will help to get json value from webBrowser.After this you may use like this: 你必须使用JSONParser类。它将有助于从webBrowser获取json值。之后你可以像这样使用:

JSONObjcet object=getJSONObject("result");
JSONArray arr=object.getJSONArray("employees");
for(int i=0;i<arr.length;i++){
JSONObject obj1=arr.getJSONObject(i);
String firstName=obj1.getString("firstName");
String lastName=obj1.getString("lastName");
}

I Hope this one help to you :) 我希望这个对你有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM