--------------------------------------------AndroidManifest.xml---------------------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kawa.ch32"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
--------------------------------------------activity_main.xml------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="getJSONArray" />
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="getJSONObject" />
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="getJSON" />
</LinearLayout>
--------------------------------------------MainActivity.java--------------------------------------
package com.kawa.ch32;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.kawa.ch32.util.JsonUtil;
public class MainActivity extends Activity {
private Button btn_array;
private Button btn_object;
private Button btn_json;
private String URL_JSONARRAY = "http://192.168.1.105:8080/com.kawa.ch32.web/JSONArray";
private String URL_JSONOBJECT = "http://192.168.1.105:8080/com.kawa.ch32.web/JSONObject";
private String URL_JSON = "http://192.168.1.105:8080/com.kawa.ch32.web/JSON";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setListeners();
}
private void findViews() {
btn_array = (Button) findViewById(R.id.btn1);
btn_object = (Button) findViewById(R.id.btn2);
btn_json = (Button) findViewById(R.id.btn3);
}
private void setListeners() {
btn_array.setOnClickListener(onClickListener);
btn_object.setOnClickListener(onClickListener);
btn_json.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn1:
try {
showResult(JsonUtil.getJSONArray(URL_JSONARRAY));
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case R.id.btn2:
try {
showResult(JsonUtil.getJSONObject(URL_JSONOBJECT));
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btn3:
try {
showResult(JsonUtil.getJSON(URL_JSON));
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
};
private void showResult(List<Map<String, String>> jsonList) {
StringBuffer result = new StringBuffer();
try {
for (Map<String, String> map : jsonList) {
String id = map.get("id");
String name = map.get("name");
result.append(id).append("--").append(name);
}
new AlertDialog.Builder(this).setTitle("json")
.setMessage(result.toString()).setPositiveButton("ok", null).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------------------JsonUtil.java------------------------------------------
package com.kawa.ch32.util;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
public class JsonUtil {
/**
* 获取"数组形式"的JSON数据,
* 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]
* @param path 网页路径
* @return 返回List
* @throws Exception
*/
public static List<Map<String, String>> getJSONArray(String path)
throws Exception {
String json = null;
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 单位是毫秒,设置超时时间为5秒
conn.setConnectTimeout(5 * 1000);
// HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
conn.setRequestMethod("GET");
// 判断请求码是否是200码,否则失败
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream(); // 获取输入流
byte[] data = readStream(is); // 把输入流转换成字符数组
json = new String(data); // 把字符数组转换成字符串
// 数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]
// 数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// 每条记录又由几个Object对象组成
JSONObject item = jsonArray.getJSONObject(i);
int id = item.getInt("id"); // 获取对象对应的值
String name = item.getString("name");
map = new HashMap<String, String>(); // 存放到MAP里面
map.put("id", id + "");
map.put("name", name);
list.add(map);
}
}
return list;
}
/**
* 获取"对象形式"的JSON数据,
* 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
* @param path 网页路径
* @return 返回List
* @throws Exception
*/
public static List<Map<String, String>> getJSONObject(String path)
throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
// 利用HttpURLConnection对象,我们可以从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
// HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
conn.setRequestMethod("GET");
// 判断请求码是否是200码,否则失败
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream(); // 获取输入流
byte[] data = readStream(is); // 把输入流转换成字符数组
String json = new String(data); // 把字符数组转换成字符串
// 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
// 返回的数据形式是一个Object类型,所以可以直接转换成一个Object
JSONObject jsonObject = new JSONObject(json);
int total = jsonObject.getInt("total");
Boolean success = jsonObject.getBoolean("success");
// 里面有一个数组数据,可以用getJSONArray获取数组
JSONArray jsonArray = jsonObject.getJSONArray("arrayData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
int id = item.getInt("id"); // 获取对象对应的值
String name = item.getString("name");
map = new HashMap<String, String>(); // 存放到MAP里面
map.put("id", id + "");
map.put("name", name);
list.add(map);
}
}
return list;
}
/**
* 获取类型复杂的JSON数据
*数据形式:
{"name":"小猪",
"age":23,
"content":{"questionsTotal":2,
"questions": [ { "question": "what's your name?", "answer": "小猪"},
{"question": "what's your age", "answer": "23"}]
}
}
* @param path 网页路径
* @return 返回List
* @throws Exception
*/
public static List<Map<String, String>> getJSON(String path) throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
// HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
InputStream is = conn.getInputStream(); // 获取输入流
byte[] data = readStream(is); // 把输入流转换成字符数组
String json = new String(data); // 把字符数组转换成字符串
/*
* 数据形式:
* {"name":"小猪",
* "age":23,
* "content":{"questionsTotal":2,
* "questions": [ { "question": "what's your name?", "answer": "小猪"},
* {"question": "what's your age", "answer":
* "23"}]
* }
* }
*/
// 返回的数据形式是一个Object类型,所以可以直接转换成一个Object
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
Log.i("abc", "name:" + name + " | age:" + age); // 测试数据
// 获取对象中的对象
JSONObject contentObject = jsonObject.getJSONObject("content");
// 获取对象中的一个值
String questionsTotal = contentObject.getString("questionsTotal");
// 获取对象中的数组
JSONArray contentArray = contentObject.getJSONArray("questions");
for (int i = 0; i < contentArray.length(); i++) {
JSONObject item = contentArray.getJSONObject(i); // 得到每个对象
String question = item.getString("question"); // 获取对象对应的值
String answer = item.getString("answer");
map = new HashMap<String, String>(); // 存放到MAP里面
map.put("question", question);
map.put("answer", answer);
list.add(map);
}
}
return list;
}
/**
* 把输入流转换成字符数组
* @param inputStream 输入流
* @return 字符数组
* @throws Exception
*/
public static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();
return bout.toByteArray();
}
}
--------------------------------------------结果----------------------------------------------------
War包放入tomcat
启动tomcat,访问网页地址
本机IP
客户端效果
点击getJSONArray按钮
点击getJSONObject按钮
点击getJSON按钮