Android解析json数据
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 ListgetlistPerson() { List list = new ArrayList (); 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 getListString() { List list = new ArrayList (); 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
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 ListgetPersons(String key, String jsonString) { List list = new ArrayList (); //{"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 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) { // TODO: handle exception } return list; } public static List > listKeyMaps(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); Map map = new HashMap (); Iterator 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());
分享文章:Android解析json数据
标题链接:http://azwzsj.com/article/jppsip.html