Android中数据文件解析(Json解析【从服务器端获取数据并且解析,显示在客户端上面】)

首先说一下Json数据的最基本的特点,Json数据是一系列的键值对的集合,和XML数据来比,Json数据的体积更加小,传输效率高,易解析,不过可读性不高;

因为这次要从服务器端得到Json数据,并且通过解析之后把解析后的数据显示在Android客户端中,首先部署服务器端代码(直接使用Jsp/Servlet):

构造的Json数据如下:

[{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]


[一]服务器端(Person.java省略):

①:数据构造JsonService.java

  1. public class JsonService {
  2. public static List getListPerson() {
  3. List mLists = new ArrayList();
  4. mLists.add(new Person("张三", "北京", 20));
  5. mLists.add(new Person("李四", "上海", 30));
  6. mLists.add(new Person("王五", "深圳", 35));
  7. return mLists;
  8. }
复制代码
②:Servlet的代码(包括构造Json数据,没有使用Json数据转换方法)JsonServlet.java

  1. public void doGet(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {
  3. response.setContentType("text/html");
  4. response.setCharacterEncoding("UTF-8");
  5. PrintWriter out = response.getWriter();
  6. List persons = JsonService.getListPerson();
  7. StringBuffer sb = new StringBuffer();
  8. sb.append('[');
  9. for (Person person : persons) {
  10. sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(
  11. ",");
  12. sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
  13. sb.append("\"age\":").append(person.getAge());
  14. sb.append('}').append(",");
  15. }
  16. sb.deleteCharAt(sb.length() - 1);
  17. sb.append(']');
  18. out.write(new String(sb));
  19. out.flush();
  20. out.close();
  21. }
复制代码

复制代码
③:部署到Tomact 浏览器输入http://localhost/JsonWeb/JsonServlet直接访问结果如下: 0_1330066556axYL.gif
2012-3-15 09:13:51 上传
下载附件 (9.56 KB)
至此服务器端代码编码完成,下面进行客户端代码编写; (二)客户端(Person类,和展示数据的布局文件因为简单省去)
①:获取服务器端的Json数据并且解析的工具类JsonParse.java
必要的需要导入的包省去
  1. public class JsonParse {
  2. /**
  3. * 解析Json数据
  4. *
  5. * @param urlPath
  6. * @return mlists
  7. * @throws Exception
  8. */
  9. public static List getListPerson(String urlPath) throws Exception {
  10. List mlists = new ArrayList();
  11. byte[] data = readParse(urlPath);
  12. JSONArray array = new JSONArray(new String(data));
  13. for (int i = 0; i < array.length(); i++) {
  14. JSONObject item = array.getJSONObject(i);
  15. String name = item.getString("name");
  16. String address = item.getString("address");
  17. int age = item.getInt("age");
  18. mlists.add(new Person(name, address, age));
  19. }
  20. return mlists;
  21. }
  22. /**
  23. * 从指定的url中获取字节数组
  24. *
  25. * @param urlPath
  26. * @return 字节数组
  27. * @throws Exception
  28. */
  29. public static byte[] readParse(String urlPath) throws Exception {
  30. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  31. byte[] data = new byte[1024];
  32. int len = 0;
  33. URL url = new URL(urlPath);
  34. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  35. InputStream inStream = conn.getInputStream();
  36. while ((len = inStream.read(data)) != -1) {
  37. outStream.write(data, 0, len);
  38. }
  39. inStream.close();
  40. return outStream.toByteArray();
  41. }
  42. }
复制代码
②:主Activity类
  1. public class MainActivity extends Activity {
  2. private Button mButton;
  3. private ListView mListView;
  4. //使用IP不能使用localhost或者127.0.0.1,因为android模拟器默认绑定这个IP,这里应该访问局域网IP
  5. private static final String urlPath = "http://10.16.31.207/JsonWeb/JsonServlet";
  6. private static final String TAG = "MainActivity";
  7. private List persons;
  8. @Override
  9. public void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.main);
  12. mButton = (Button) findViewById(R.id.button1);
  13. mListView = (ListView) findViewById(R.id.listView1);
  14. mButton.setOnClickListener(new MyOnClickListener());
  15. }

  16. private class MyOnClickListener implements OnClickListener {
  17. @Override
  18. public void onClick(View v) {
  19. try {
  20. // 得到Json解析成功之后数据
  21. persons = JsonParse.getListPerson(urlPath);
  22. List> data = new ArrayList>();
  23. for (int i = 0; i < persons.size(); i++) {
  24. HashMap map = new HashMap();
  25. map.put("name", persons.get(i).getName());
  26. map.put("address", persons.get(i).getAddress());
  27. map.put("age", persons.get(i).getAge());
  28. data.add(map);
  29. }
  30. //初始化适配器,并且绑定数据
  31. SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
  32. data, R.layout.listview_item, new String[] { "name",
  33. "address", "age" }, new int[] { R.id.textView1,
  34. R.id.textView2, R.id.textView3 });
  35. mListView.setAdapter(_Adapter);
  36. } catch (Exception e) {
  37. Toast.makeText(MainActivity.this, "解析失败", 2000).show();
  38. Log.i(TAG, e.toString());

  39. }
  40. }
  41. }
复制代码
至此服务器端和客户端编码介绍,运行android应用结果截图:

0_1330067381FcfP.gif


转自:http://www.apkbus.com/android-24098-1-1.html

你可能感兴趣的:(android开发,json,服务器,android,exception,string,listview)