Android中解析Json數據

一、原理分析

vcD4KPHA+tv6horT6wuvKtc/WKNX7zNe0+sLrtcTPwtTYtdjWt2h0dHA6Ly9kb3dubG9hZC5jc2RuLm5ldC9kZXRhaWwvY2FpaG9uZ3NoaWppZTYvNjcwMTI3OSk8L3A+CjxwPsv50OjSqrXESlNPTrXEz+C52LXEamFysPy1xM/C1Ni12Na3aHR0cDovL2Rvd25sb2FkLmNzZG4ubmV0L2RldGFpbC9jYWlob25nc2hpamllNi82NzAxMjg1PC9wPgo8cD48YnI+CjwvcD4KPHA+MaGit/7O8cb3tsso1vfSqtPD09rJ+rPJSlNPTiYjMjY2ODQ7yr21xNfWt/u0rik8L3A+CjxwPiAgMSlKc29uQWN0aW9uPC9wPgo8cD48cHJlIGNsYXNzPQ==”brush:java;”>package com.njupt.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.njupt.service.JsonService;
import com.njupt.tools.JsonTools;

public class JsonAction extends HttpServlet {

private JsonService service;
/**
* Constructor of the object.
*/
public JsonAction() {
super();
}

/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts “destroy” string in log
// Put your code here
}

/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

public 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 = JsonTools.createJsonString(“persons”, service.getListPerson());

String jsonString = “”;
String action_flag = request.getParameter(“action_flag”);
if(action_flag.equals(“person”)){
jsonString = JsonTools.createJsonString(“person”, service.getPerson());
}else if(action_flag.equals(“persons”)){
jsonString = JsonTools.createJsonString(“persons”, service.getListPerson());
}else if(action_flag.equals(“liststring”)){
jsonString = JsonTools.createJsonString(“liststring”, service.getListString());
}else if(action_flag.equals(“listmap”)){
jsonString = JsonTools.createJsonString(“listmap”, service.getListMaps());

}
out.println(jsonString);
out.flush();
out.close();
}

/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
service = new JsonService();
}

}

2)JsonService

package com.njupt.service;

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

import org.apache.commons.collections.map.HashedMap;

import com.njupt.pojo.Person;

public class JsonService {
	public JsonService() {
		// TODO Auto-generated constructor stub
	}
	
	public Person getPerson(){
		Person person = new Person(1001,"zhangzetian","beijing");
	    
		return person;
	}
	
	
	public List getListPerson(){
		List list = new ArrayList();
		
		Person person1 = new Person(1003,"huangjundong","beijing");
		Person person2 = new Person(1004,"zhangzetian","guangdong");
		
		list.add(person1);
		list.add(person2);
	 
		return list;
	}
	
	public List getListString(){
		List list = new ArrayList();
		list.add("beijing");
		list.add("shanghai");
		list.add("hunan");
		
		return list;
	}
	
	public List<Map> getListMaps(){
		List<Map> list = new ArrayList<Map>();
		Map map1 = new HashMap();
	    map1.put("id", 1001);
	    map1.put("name", "huangjundong");
	    map1.put("address", "beijing");
	    
	    Map map2 = new HashMap();
	    map2.put("id", 1002);
	    map2.put("name", "zhangzetian");
	    map2.put("address", "beijing");
	    
	    list.add(map1);
	    list.add(map2);
	    
	    return list;
	}
}

3)Person

package com.njupt.pojo;

public class Person {
	private int id;
	private String name;
	private String address;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	public Person(int id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

	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 [address=" + address + ", id=" + id + ", name=" + name
				+ "]";
	}
	
	
}

4)JsonTools

package com.njupt.tools;

import net.sf.json.JSONObject;

/**
 * 服務器端的JSONTools主要用於生成JSON
 * @author Administrator
 *
 */
public class JsonTools {

	public JsonTools() {
		// TODO Auto-generated constructor stub
	}
	
	
	public static String createJsonString(String key,Object value){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(key, value);
		return jsonObject.toString();
	}
}

2、Android端

1)main.xml


    
     

2)MainActivity

package com.njupt.android_json;

import java.util.List;
import java.util.Map;

import com.njupt.pojo.Person;
import com.njupt.tools.JsonTools;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private Button person;
	private Button persons;
	private Button liststring;
	private Button listmap;

	private String path = "https://192.168.1.104:8080/JsonProject/servlet/JsonAction";
	
	private static final String TAG = "MAIN";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		person = (Button) findViewById(R.id.person);
		persons = (Button) findViewById(R.id.persons);
		liststring = (Button) findViewById(R.id.liststring);
		listmap = (Button) findViewById(R.id.listmap);
		
		person.setOnClickListener(this);
		persons.setOnClickListener(this);
		liststring.setOnClickListener(this);
		listmap.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.person:

			String tempPath = path;
			tempPath += "?action_flag=person";
			String jsonString = HttpUtils.getJsonContent(tempPath);
			Person person = JsonTools.getPerson("person", jsonString);
			Log.i(TAG, person.toString());
			
			Toast.makeText(this, person.toString(), 1).show();
			
			break;

		case R.id.persons:
			
			tempPath = path;
			tempPath += "?action_flag=persons";
			jsonString = HttpUtils.getJsonContent(tempPath);
			List list = JsonTools.getPersons("persons", jsonString);
			Log.i(TAG, list.toString());
			
			Toast.makeText(this, list.toString(), 1).show();
			
			break;
		case R.id.liststring:

			tempPath = path;
			tempPath += "?action_flag=liststring";
			jsonString = HttpUtils.getJsonContent(tempPath);
			List list1 = JsonTools.getList("liststring", jsonString);
			Log.i(TAG, list1.toString());
			
			Toast.makeText(this, list1.toString(), 1).show();
			
			break;

		case R.id.listmap:

			tempPath = path;
			tempPath += "?action_flag=listmap";
			jsonString = HttpUtils.getJsonContent(tempPath);
			List<Map> list4 = JsonTools.listKeyMaps("listmap", jsonString);
			Log.i(TAG, list4.toString());
			
			Toast.makeText(this, list4.toString(), 1).show();
			
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

3)HttpUtils

package com.njupt.android_json;

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

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static String getJsonContent(String url_path) {
		try {
			URL url = new URL(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 (Exception e) {
			e.printStackTrace();
		}
		
		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(Exception e){
			e.printStackTrace();
		}
		return jsonString;
	}
}

4)Person

package com.njupt.pojo;

public class Person {
	private int id;
	private String name;
	private String address;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	public Person(int id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

	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 [address=" + address + ", id=" + id + ", name=" + name
				+ "]";
	}
	
	
}

5)JsonTools

package com.njupt.tools;

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.JSONObject;

import com.njupt.pojo.Person;

/**
 * 客戶端的JsonTools主要用來解析JSON
 * @author Administrator
 *
 */
public class JsonTools {

	public JsonTools() {
		// TODO Auto-generated constructor stub
	}
	
	
	public static Person getPerson(String key,String jsonString){
		Person person = new Person();
		
		try{
			/**
			 * 解析就是一個person的情況
			 * {"person":{"address":"beijing","id":1001,"name":"jack"}}
			 */
			JSONObject jsonObject = new JSONObject(jsonString);//獲得的是: {"person":{"address":"beijing","id":1001,"name":"jack"}}
			JSONObject personObject = jsonObject.getJSONObject(key);//獲得的是: {"address":"beijing","id":1001,"name":"jack"}
			
			person.setId(personObject.getInt("id"));
			person.setName(personObject.getString("name"));
			person.setAddress(personObject.getString("address"));
		}catch(Exception e){
			
		}
		
		return person;
	}
	
	
	/**
	 * 解析List的情況
	 * {"persons":[{"address":"beijing","id":1003,"name":"huangjundong"},{"address":"guangdong","id":1004,"name":"zhangzetian"}]}
	 * @param key
	 * @param jsonString
	 * @return
	 */
	public static List getPersons(String key,String jsonString){
		List list = new ArrayList();
		
		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){
			e.printStackTrace();
		}
		
		return list;
	}
	
	
	/**
	 * 解析List的情況
	 * {"liststring":["beijing","shanghai","hunan"]}
	 * @param key
	 * @param jsonString
	 * @return
	 */
	public static List getList(String key,String jsonString){
		List list = new ArrayList();
		
		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){
			e.printStackTrace();
		}
		
		return list;
	}
	
	
	/**
	 * 解析List的情況
	 * {"listmap":[{"id":1001,"address":"beijing","name":"huangjundong"},{"id":1002,"address":"beijing","name":"zhangzetian"}]}
	 * @param key
	 * @param jsonString
	 * @return
	 */
	public static List<Map> listKeyMaps(String key,String jsonString){
		List<Map> list = new ArrayList<Map>();
		
		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 map = new HashMap();
				Iterator iterator = jsonObject2.keys();
				
				while(iterator.hasNext()){
					String jsonKey = iterator.next();
					Object jsonValue = jsonObject2.get(jsonKey);
					
					if(jsonValue == null){
							jsonValue = "";
					}
					
					map.put(jsonKey, jsonValue);
				}
				
				list.add(map);
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
}

發佈留言