如何解析android-php json web服务响应


How to parse android-php json webservice response

我是android新手,学习了一点。我在android和php之间传递json对象。

我有这个代码发送json对象发送json对象到服务器。它运行得很好。它也在Toast上印刷。但是任何请帮助我如何阅读和显示从我的服务器到我的应用程序的响应?

我的代码看起来像
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();
    }
}

假设你的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.

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)并在您想要的任何视图上显示。希望对大家有所帮助