当前位置: 代码迷 >> JavaScript >> Android解析JSON形式(二) 客户端解析SON数据
  详细解决方案

Android解析JSON形式(二) 客户端解析SON数据

热度:328   发布时间:2013-03-04 17:22:12.0
Android解析JSON方式(二) 客户端解析SON数据

在上一篇中搭建了服务器端的程序,这篇我们来建立一个Android项目,来访问服务器取得JSON格式数据,并解析JSON数据格式,输出到日志控制台。

我们建立的项目目录结构如下:



运行的界面截图:



当我们分别点击四个按钮,可以看到控制台的输出日志:



以下是源代码:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	<Button 
	    android:id="@+id/person"
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析person数据" 
        android:onClick="click"/>
	<Button 
	    android:id="@+id/persons"
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析persons数据" 
        android:onClick="click"/>
	<Button 
	    android:id="@+id/listString"
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析listString数据" 
        android:onClick="click"/>
	<Button 
	    android:id="@+id/listMap"
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析listMap数据" 
        android:onClick="click"/>
</LinearLayout>

MainActivity.java

package com.json.activity;

import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.json.bean.Person;
import com.json.util.HttpUtils;
import com.json.util.JsonTools;

public class MainActivity extends Activity {
	private static String PATH = "http://192.168.56.1:8080/JsonProject/servlet/JsonServlet";
    private static final String TAG = "MainActivity";
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void click(View v){
    	switch (v.getId()) {
		case R.id.person:
			String path1=PATH+"?action_flag=person";
			String jsonString1 = HttpUtils.getJsonContent(path1);
			Person person = JsonTools.getPerson("person", jsonString1);
			Log.i(TAG, person.toString());
			break;
		case R.id.persons:
			String path2=PATH+"?action_flag=persons";
			String jsonString2 = HttpUtils.getJsonContent(path2);
			List<Person> list2 = JsonTools.getPersons("persons", jsonString2);
			Log.i(TAG, list2.toString());	
			break;
		case R.id.listString:
			String path3=PATH+"?action_flag=listString";
			String jsonString3 = HttpUtils.getJsonContent(path3);
			List<String> list3 = JsonTools.getList("listString", jsonString3);
			Log.i(TAG, list3.toString());
			
			break;
		case R.id.listMap:
			String path4=PATH+"?action_flag=listMap";
			String jsonString4 = HttpUtils.getJsonContent(path4);
			List<Map<String,Object>> list4 = JsonTools.getListMap("listMap", jsonString4);
			Log.i(TAG, list4.toString());
			break;
		}
    }
}

Person.java

package com.json.bean;

public class Person {
	private int id;
	private String name;
	private String address;
	
	public Person() {
		super();
	}
	public Person(int id, String name, String addrss) {
		super();
		this.id = id;
		this.name = name;
		this.address = addrss;
	}
	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 [addrss=" + address + ", id=" + id + ", name=" + name
				+ "]";
	}
	
}

HttpUtils.java

package com.json.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {

	public 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 changeInputStream(connection.getInputStream());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将一个输入流转换成指定编码的字符串  
	 * @param inputStream
	 * @return
	 */
	private static String changeInputStream(InputStream inputStream) {
		String jsonString = "";
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while((len=inputStream.read(data))!=-1){
				outputStream.write(data,0,len);
			}
			jsonString = new String(outputStream.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonString;
	}
}

JsonTools.java

package com.json.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.json.bean.Person;

/**
 * 完成对JSON数据的解析
 * @author wulianghuan
 *
 */
public class JsonTools {

	public JsonTools() {
		
	}
	
	/**
	 * 获取对象数据
	 * @param key
	 * @param jsonString
	 * @return
	 */
	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 (JSONException e) {
			e.printStackTrace();
		}
		return person;
	}
	
	/**
	 * 获取对象数组数据
	 * @param key
	 * @param jsonString
	 * @return
	 */
	public static List<Person> getPersons(String key,String jsonString){
		List<Person> list = new ArrayList<Person>();
		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			//返回json的数组
			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 (JSONException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	/**
	 * 获取String数组数据
	 * @param key
	 * @param jsonString
	 * @return
	 */
	public static List<String> getList(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 (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 获取对象的Map集合数据
	 * @param key
	 * @param jsonString
	 * @return
	 */
	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 (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}
}