您好,登錄后才能下訂單哦!
1.JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一個子集。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。這些特性使JSON成為理想的數據交換語言。 易于人閱讀和編寫,同時也易于機器解析和生成(網絡傳輸速度)。
2.json的數據格式
1>object
{
"name"aaaaaaaaa:"jackson",
"age":100
}
2>數組
{
“students”:
[
{"name":"jackson","age":100},
{"name":"yu","age":22}
]
}
實例:把服務器端的數據生成json數據格式的返回,在Android客戶端獲取json數據,解析該json格式的數據。
1.使用Json 需要用到一下幾個包,下載這下包放在服務器的項目工程下
json-lib-2.3-jdk15.jar commons-beanutils-1.7.0.jar commons-httpclient-3.1.jar commons-lang-2.3.jar commons-logging-1.0.4.jar commons-collections-3.1.jar ezmorph-1.0.3.jar 2. 在Myeclipse 下新建一個項目,首先新建一個 Json的工具類,通過調用該工具類,可以把數據轉換成Json格式的
public class JsonTools { public JsonTools() { // TODO Auto-generated constructor stub } /** * @param key * 表示json字符串的頭信息 * @param object * 是對解析的集合的類型 * @return */ public static String createJsonString(String key, Object value) { JSONObject jsonObject = new JSONObject(); jsonObject.put(key, value); return jsonObject.toString(); }
3.給對象賦值
package com.json.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.json.domain.Person; public class JsonService { public JsonService() { } /* * {"person":{"address":"beijing","id":1001,"name":"jack"}} */ public Person getPerson() { Person person = new Person(1001, "yu", "beijing"); return person; } /* * {"persons":[{"address":"guangxi","id":1001,"name":"jack"},{"address":"guangdong","id":1002,"name":"rose"}]} */ public List<Person> getlistPerson() { List<Person> list = new ArrayList<Person>(); Person person1 = new Person(1001, "yu", "guangxi"); Person person2 = new Person(1002, "rose", "guangdong"); list.add(person1); list.add(person2); return list; } /* * {"liststring":["beijing","shanghai","hunan"]} */ public List<String> getListString() { List<String> list = new ArrayList<String>(); list.add("beijing"); list.add("shanghai"); list.add("hunan"); return list; } //{"listmap":[{"id":1001,"address":"beijing","name":"jack"},{"id":1002,"address":"shanghai","name":"rose"}]} public List<Map<String, Object>> getListMaps() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("id", 1001); map1.put("name", "jack"); map1.put("address", "beijing"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", 1002); map2.put("name", "rose"); map2.put("address", "shanghai"); list.add(map1); list.add(map2); return list; } }
4.新建一個Servlet 調用 生成json的方法,然后把生成的json格式的數據輸出到客戶端
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 = ""; String action_flag =request.getParameter("action_flag"); if (action_flag.equals("person")) { jsonString = JsonTools.createJsonString("person", service .getPerson()); System.out.println("person"); } else if (action_flag.equals("persons")) { jsonString = JsonTools.createJsonString("persons", service .getlistPerson()); System.out.println("persons"); } else if (action_flag.equals("liststring")) { jsonString = JsonTools.createJsonString("liststring", service .getListString()); System.out.println("liststring"); } else if (action_flag.equals("listmap")) { jsonString = JsonTools.createJsonString("listmap", service .getListMaps()); System.out.println("listmap"); } out.println(jsonString); out.flush(); out.close(); }
5.搭建Android客戶端,新建一個HttpClient工具類,獲取服務器端json格式的數據
package com.android.myjson.http; import java.io.ByteArrayOutputStream; import java.io.IOException; 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) { // TODO: handle exception } return ""; } private static String changeInputStream(InputStream inputStream) { // TODO Auto-generated method stub 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) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonString; } }
6.新建一個Json 工具類解析json 數據
package com.android.myjson.json; 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.android.myjson.domain.Person; public class JsonTools { public JsonTools() { // TODO Auto-generated constructor stub } public static Person getPerson(String key, String jsonString) { Person person = new Person(); //{"person":{"address":"beijing","id":1001,"name":"jack"}} try { JSONObject jsonObject = new JSONObject(jsonString); JSONObject personObject = jsonObject.getJSONObject("person"); 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>(); //{"persons":[{"address":"guangxi","id":1001,"name":"jack"},{"address":"guangdong","id":1002,"name":"rose"}]} 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> 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 (Exception e) { // TODO: handle exception } return list; } public static List<Map<String, Object>> listKeyMaps(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) { // TODO: handle exception } return list; } }
7.打印出解析后的數據
String path = "http://192.168.191.1:8080/jsonProject/servlet/JsonAction?action_flag=person"; String jsonString = HttpUtils.getJsonContent(path); Person person = JsonTools.getPerson("person", jsonString); Log.i(TAG, person.toString());
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。