简体   繁体   English

如何解析android-php json webservice响应

[英]How to parse android-php json webservice response

I am new to android and studying a bit. 我是Android新手,正在学习。 I am in a hard duty to pass json objects between android and php. 我有责任在android和php之间传递json对象。

I have this code to send json object to send json object to server. 我有这段代码来发送json对象,以将json对象发送到服务器。 Its pretty working well. 它工作得很好。 Its printing in Toast also. 其在吐司上的印刷也。 But Can any please help me how to read and show the response from my server to my application ? 但是,请问有什么可以帮助我阅读和显示服务器对应用程序的响应的信息吗?

my code looks like 我的代码看起来像

package com.test.webservice;


import android.util.Log;
import android.view.Menu;
import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class MainActivity extends Activity {

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



        String path = "http://www.mysite.com/app.php";

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                // Limit
        HttpResponse response;
        JSONObject json = new JSONObject();
        try {
            HttpPost post = new HttpPost(path);
            json.put("service", "GOOGLE");
            json.put("name", "My Name");
            Log.i("jason Object", json.toString());
            post.setHeader("json", json.toString());
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(se);
            response = client.execute(post);
            /* Checking response */
            if (response != null) {
                InputStream in = response.getEntity().getContent(); // Get the
                                                                    // data in
                                                                        // the
                                                                        // entity
                String a = convertStreamToString(in);

                Toast.makeText(getApplicationContext(), 
                        a, Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }






    }

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

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}

Suppose if you have an array called response on your php side like below and then I assume you are populating data into that array in this way: 假设如果您的php端像下面这样有一个名为response的数组,那么我假设您是以这种方式将数据填充到该数组中:

$response = array();
$response["intvalue"] = 1234;
$response["stringmessage"] = "Data from the server";

echo json_encode($response);// Here you are echoing json response. So in the inputstream you would get the json data. You need to extract it over there and can display according to your requirement.

Extraction at android side: 在Android端提取:

Here you need to convert the String(which you are displaying in the toast) to json object in the below way: 在这里,您需要按照以下方式将String(在烤面包中显示)转换为json对象:

JSONObject json = stringToJsonobj(a);  // a is your string response

int passedinteger = json.getInt("intvalue");
String passedStringValue = json.getString("stringmessage");

public JSONObject stringToJsonobj(String result)
    {
        JSONObject jObj = null;
            try {

            jObj = new JSONObject(result);          

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }

         return jObj; 
}

In this way, you can get an individual values(passedinteger, passedstringvalue) and display on whatever views you want. 这样,您可以获得individual values(passedinteger, passedstringvalue)并显示在所需的任何视图上。 Hope this helps 希望这可以帮助

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

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