先写服务器端的代码,先写一个person对象
public class Person {
private int id;
private String name;
private String address;
public Person() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", address=" + address
+ "]";
}
public Person(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
}
初始化一下person对象
public class JsonService {
//一个person对象
public Person getPerson(){
Person person=new Person(1001,"hang","suqian");
return person;
}
}
服务器端json的工具类
public class JsonToos {
public static String CreateJsonString(String key,Object value){
//生成json的string
JSONObject jsonObject=new JSONObject();
jsonObject.put(key,value);
return jsonObject.toString();
}
}
服务端的servlet
public class JsonAction extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private JsonService service;
/**
* @see HttpServlet#HttpServlet()
*/
public JsonAction() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
String jsonString=JsonToos.CreateJsonString("person",service.getPerson());
out.println(jsonString);
out.flush();
out.close();
}
@Override
public void init() throws ServletException {
service=new JsonService();
}
}
注意
<uses-permission android:name="android.permission.INTERNET"/>
这个一定要加的,网络访问权限
定义person的对象同上
下面是http的工具类,主要是http访问,获取json的字符串
public class HttpUtils {
public static String getJsonContent(String path){
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
int code=connection.getResponseCode();
if(code==200){
return changeInputString(connection.getInputStream());
}
} catch (Exception e) {
// TODO: handle exception
}
return "";
}
private static String changeInputString(InputStream inputStream) {
String jsonString="";
ByteArrayOutputStream outPutStream=new ByteArrayOutputStream();
byte[] data=new byte[1024];
int len=0;
try {
while((len=inputStream.read(data))!=-1){
outPutStream.write(data, 0, len);
}
jsonString=new String(outPutStream.toByteArray());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
}
下面为解析json字符串,把值赋给person对象
public class JsonTools {
public static Person getPerson(String key, String jsonString) {
Person person = new Person();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject personObject = jsonObject.getJSONObject(key);
person.setId(personObject.getInt("id"));
person.setName(personObject.getString("name"));
person.setAddress(personObject.getString("address"));
} catch (Exception e) {
// TODO: handle exception
}
return person;
}
public static List<Person> getPersons(String key, String jsonString) {
List<Person> list = new ArrayList<Person>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Person person = new Person();
person.setId(jsonObject2.getInt("id"));
person.setName(jsonObject2.getString("name"));
person.setAddress(jsonObject2.getString("address"));
list.add(person);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List<String> getlistString(String key, String jsonString) {
List<String> list = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
String msg = jsonArray.getString(i);
list.add(msg);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List<Map<String,Object>> getlistMap(String key, String jsonString){
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map<String,Object> map=new HashMap<String, Object>();
Iterator<String> iterator=jsonObject2.keys();
while(iterator.hasNext()){
String json_key=iterator.next();
Object json_value=jsonObject2.get(json_key);
if(json_value==null){
json_value="";
}
map.put(json_key, json_value);
}
list.add(map);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
}
android点击button触发的事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.person:
path="http://192.168.123.1/http/JsonAction";
String jsonstring=HttpUtils.getJsonContent(path);
Log.i(TAG,"1212"+jsonstring);
Person person=JsonTools.getPerson("person", jsonstring);
Log.i(TAG,person.toString());
break;
default:
break;
}
}
}
更多参考:http://blog.csdn.net/zc527/article/details/44465053