Android使用json与服务器交互

来源:互联网 发布:蓝翔高级技工学校知乎 编辑:程序博客网 时间:2024/05/07 16:35

json是一种轻量级的数据交换格式,易于人们阅读编写。

格式:json对象是无序键值对,开始结尾为{   };键值之间用: ,对象之间用,隔开。

Android端

1从服务器端获取数据并显示代码如下:

 public void doHttpGetJSON(View view) throws IOException, JSONException {                DefaultHttpClient httpClient = new DefaultHttpClient();        //指定服务器端URL        HttpGet get = new HttpGet("http://10.4.30.228:8080/PersonForAndroid/person");        HttpResponse rsp = httpClient.execute(get);        //获取响应的实体        HttpEntity httpEntity = rsp.getEntity();        //将响应的实体转换为字符串        String jsonString = EntityUtils.toString(httpEntity);        //服务器端返回的数据格式为:[{"name":"Johnny","gender":"Male","title":"Programmer"},{"name":"Kevin","gender":"Male","title":"Manager"}]        //是一个JSON数组,因此使用JSONArray将字符串转换为JSONArray        //如果服务器端返回的是JSON字符串:{"name":"Johnny","gender":"Male","title":"Programmer"},则使用JSONObject jsonObject=new JSONObject(jsonString);        JSONArray jsonArray=new JSONArray(jsonString);        String resultsString="";        //遍历JSONArray,将结果输出        for (int i = 0; i < jsonArray.length(); i++) {            JSONObject jsonObj = jsonArray.getJSONObject(i);            String name = jsonObj.getString("name");            String gender = jsonObj.getString("gender");            String title = jsonObj.getString("title");            resultsString += title + " " + name + " is " + gender+"\r\n";        }        TextView getTextView = (TextView) findViewById(R.id.jsonGetTextView);        getTextView.setText(resultsString);    }
2向服务器提交JSON格式数据
 public void doHttpPostJSON(View view) throws IOException, JSONException {        //定义一个JSON,用于向服务器提交数据        JSONObject jsonObj = new JSONObject();        jsonObj.put("name", getTextFromView(R.id.name))                .put("gender", getTextFromView(R.id.gender))                .put("title", getTextFromView(R.id.title));        String jsonString = jsonObj.toString();        //指定Post参数        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);        nameValuePairs.add(new BasicNameValuePair("data", jsonString));                DefaultHttpClient httpClient = new DefaultHttpClient();        HttpPost post = new HttpPost("http://10.4.30.228:8080/PersonForAndroid/person");        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));        HttpResponse rsp = httpClient.execute(post);                HttpEntity httpEntity = rsp.getEntity();        String displayString = EntityUtils.toString(httpEntity);                TextView getTextView = (TextView) findViewById(R.id.jsonPostTextView);        getTextView.setText(displayString);    }


0 0
原创粉丝点击