如何解析android-php json webservice响应

时间:2013-05-04 07:20:27

标签: php android json web-services android-emulator

我是android新手并且学习了一下。我很难在android和php之间传递json对象。

我有这个代码发送json对象将json对象发送到服务器。它非常好用。它在吐司中的印刷也。但是,请问如何阅读并显示我的服务器对我的应用程序的响应?

我的代码看起来像

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();
    }

}

1 个答案:

答案 0 :(得分:1)

假设您的response侧有一个名为php的数组,如下所示,那么我假设您正在以这种方式将数据填充到该数组中:

$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.

在android端提取

这里你需要以下面的方式将字符串(你在toast中显示)转换为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; 
}

通过这种方式,您可以获得individual values(passedinteger, passedstringvalue)并显示您想要的任何视图。希望这有帮助