Android[中级教程]第八章 Json数据的处理

 

Android[中级教程]第八章 Json数据的处理

分类: Android中级   727人阅读  评论(2)  收藏  举报

 经过上几章的学习,相信同学们对XML解析已经得心应手了,但今天我们要解析Json数据,因为Json数据占用数据量小,因此在Android中主要数据通信还是以Json为主,而且Json数据可以跟Android进行AJAX互动,相当方便哦,好了,不多说了,看图跟代码:

先上图:

首先定义了Json数据:

  1. "persons": [   
  2. "id""1""status":"大徙弟""name""孙悟空""tool""金箍棒""number""杀死了50只妖怪" },   
  3. "id""2""status":"二徙弟""name""猪八戒""tool""九齿钉耙""number""杀死了43只妖怪" },  
  4. "id""3""status":"三徙弟""name""沙和尚""tool""降妖宝杖""number""杀死了33只妖怪" }  
  5. ]}   

接下来就是定义javaBean了,对于java开发来说,javaBean可以很方便地存储和管理数据

  1. public class Person  
  2. {  
  3.     private String id;  
  4.     private String status;  
  5.     private String name;  
  6.     private String tool;  
  7.     private String number;  
  8.       
  9.   
  10.     public String getId()  
  11.     {  
  12.         return id;  
  13.     }  
  14.     public void setId(String id)  
  15.     {  
  16.         this.id = id;  
  17.     }  
  18.     public String getStatus()  
  19.     {  
  20.         return status;  
  21.     }  
  22.     public void setStatus(String status)  
  23.     {  
  24.         this.status = status;  
  25.     }  
  26.     public String getName()  
  27.     {  
  28.         return name;  
  29.     }  
  30.     public void setName(String name)  
  31.     {  
  32.         this.name = name;  
  33.     }  
  34.     public String getTool()  
  35.     {  
  36.         return tool;  
  37.     }  
  38.     public void setTool(String tool)  
  39.     {  
  40.         this.tool = tool;  
  41.     }  
  42.     public String getNumber()  
  43.     {  
  44.         return number;  
  45.     }  
  46.     public void setNumber(String number)  
  47.     {  
  48.         this.number = number;  
  49.     }  
  50.     @Override  
  51.     public String toString()  
  52.     {  
  53.         return "Person [id=" + id + ", status=" + status + ", name=" + name  
  54.                 + ", tool=" + tool + ", number=" + number + "]";  
  55.     }  
  56.       
  57. }  

 

接下来就是 Json的处理了,定义了一个JsonHandler类

  1. import java.io.BufferedReader;  
  2. import java.io.InputStream;  
  3. import java.io.InputStreamReader;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.json.JSONArray;  
  8. import org.json.JSONObject;  
  9.   
  10. public class JsonHandler  
  11. {  
  12.     private InputStream input;  
  13.     private List<Person> persons;  
  14.     private Person person;  
  15.   
  16.     public JsonHandler()  
  17.     {  
  18.     }  
  19.   
  20.     public JsonHandler(InputStream input)  
  21.     {  
  22.         this.input = input;  
  23.     }  
  24.   
  25.     public void setInput(InputStream input)  
  26.     {  
  27.         this.input = input;  
  28.     }  
  29.   
  30.     public List<Person> getPersons()  
  31.     {  
  32.         persons = new ArrayList<Person>();  
  33.         try  
  34.         {  
  35.             //自定义方法,从输入流中取得字符串  
  36.             String json_str = getJsonString(input);  
  37.             //通过字符串生成Json对象  
  38.             JSONObject object = new JSONObject(json_str);  
  39.             //将Json对象中的persons数据转换成Json数组  
  40.             JSONArray array = object.getJSONArray("persons");  
  41.             //数组长度  
  42.             int length = array.length();  
  43.             for (int i = 0; i < length; i++)  
  44.             {  
  45.                 //将每一个数组再转换成Json对象  
  46.                 JSONObject obj = array.getJSONObject(i);  
  47.   
  48.                 person = new Person();  
  49.                 person.setId(obj.getString("id"));  
  50.                 person.setStatus(obj.getString("status"));  
  51.                 person.setName(obj.getString("name"));  
  52.                 person.setTool(obj.getString("tool"));  
  53.                 person.setNumber(obj.getString("number"));  
  54.   
  55.                 persons.add(person);  
  56.   
  57.             }  
  58.   
  59.             return persons;  
  60.   
  61.         } catch (Exception e)  
  62.         {  
  63.             e.printStackTrace();  
  64.         }  
  65.   
  66.         return null;  
  67.     }  
  68.   
  69.     /** 
  70.      * 将输入流中数据整合成字符串 
  71.      *  
  72.      * @param input 
  73.      *            输入流 
  74.      * @return 
  75.      * @throws Exception 
  76.      */  
  77.     private String getJsonString(InputStream input) throws Exception  
  78.     {  
  79.         BufferedReader reader = new BufferedReader(new InputStreamReader(input));  
  80.         StringBuilder sb = new StringBuilder();  
  81.         for (String s = reader.readLine(); s != null; s = reader.readLine())  
  82.         {  
  83.             sb.append(s);  
  84.         }  
  85.   
  86.         return sb.toString();  
  87.     }  
  88.   
  89. }  

OK,到这里数据应该能解析出来了,可以通过测试类来测试一下,呵呵,我还是比较喜欢边测试边做下一步开发

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3.   
  4. import java.util.List;  
  5.   
  6. import android.os.Environment;  
  7. import android.test.AndroidTestCase;  
  8.   
  9. public class HandlerTest extends AndroidTestCase  
  10. {  
  11.       
  12.   
  13.     public void testJsonGetPersons()  
  14.     {  
  15.   
  16.         // 取得当前SD目录下的文件路径  
  17.         File SD_Files = Environment.getExternalStorageDirectory();  
  18.         // 取得persons.xml文件的路径,这里我是存在sdcard/data.json  
  19.         String file_path = SD_Files.getName() + File.separator + "data.json";  
  20.   
  21.         try  
  22.         {  
  23.             FileInputStream fis = new FileInputStream(new File(file_path));  
  24.             JsonHandler jsonHandler = new JsonHandler(fis);  
  25.             List<Person> persons = jsonHandler.getPersons();  
  26.             System.out.println(persons);  
  27.   
  28.         } catch (Exception e)  
  29.         {  
  30.             e.printStackTrace();  
  31.         }  
  32.   
  33.     }  
  34. }  

好,测试没问题了,那我们就上主Activity类了

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.os.Environment;  
  11. import android.widget.ListView;  
  12. import android.widget.SimpleAdapter;  
  13.   
  14. public class JsonActivity extends Activity  
  15. {  
  16.     private ListView listView;  
  17.     private SimpleAdapter adapter;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState)  
  21.     {  
  22.         // TODO Auto-generated method stub  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.xml_handler);  
  25.   
  26.         listView = (ListView) findViewById(R.id.xml_list);  
  27.         try  
  28.         {  
  29.             // 自完义适配方法  
  30.             getAdapter();  
  31.   
  32.         } catch (Exception e)  
  33.         {  
  34.             e.printStackTrace();  
  35.         }  
  36.         listView.setAdapter(adapter);  
  37.     }  
  38.   
  39.     private void getAdapter() throws Exception  
  40.     {  
  41.         List<Map<String, String>> lists = new ArrayList<Map<String, String>>();  
  42.         //取得SD卡目录  
  43.         File SD_Files = Environment.getExternalStorageDirectory();  
  44.         //取得文件路径  
  45.         String file_path = SD_Files.getName() + File.separator + "data.json";  
  46.         //Json处理  
  47.         FileInputStream fis = new FileInputStream(new File(file_path));  
  48.         JsonHandler jsonHandler = new JsonHandler(fis);  
  49.         List<Person> persons = jsonHandler.getPersons();  
  50.   
  51.         // 将persons中的数据转换到ArrayList<Map<String,String>>中  
  52.         // String>>中,因为SimpleAdapter要用这个类型的数据进行适配  
  53.         Map<String, String> map;  
  54.         for (Person p : persons)  
  55.         {  
  56.             map = new HashMap<String, String>();  
  57.   
  58.             map.put("id", p.getId());  
  59.             map.put("status", p.getStatus());  
  60.             map.put("name", p.getName());  
  61.             map.put("tool", p.getTool());  
  62.             map.put("number", p.getNumber());  
  63.   
  64.             lists.add(map);  
  65.         }  
  66.   
  67.         // HashMap<String, String>中的key  
  68.         String[] from = { "id""status""name""tool""number" };  
  69.         // list_item.xml中对应的控件ID  
  70.         int[] to = { R.id.item_id, R.id.item_status, R.id.item_name,  
  71.                 R.id.item_tool, R.id.item_number };  
  72.   
  73.         adapter = new SimpleAdapter(this, lists, R.layout.handler_list_item,  
  74.                 from, to);  
  75.     }  
  76.   
  77. }  

这里面还定义了几个Layout,也一起送上吧:

xml_handler.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.     <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  6.         android:layout_width="wrap_content" android:text="唐僧的三个徙弟"  
  7.         android:layout_height="wrap_content" android:id="@+id/textView1"  
  8.         android:paddingLeft="10dip" android:paddingBottom="10dip"></TextView>  
  9.     <ListView android:id="@+id/xml_list" android:layout_height="wrap_content"  
  10.         android:layout_width="match_parent"></ListView>  
  11.   
  12. </LinearLayout>  

handler_list_item.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" android:paddingLeft="10dip"  
  5.     android:paddingRight="10dip">  
  6.     <LinearLayout android:id="@+id/linearLayout1"  
  7.         android:layout_height="wrap_content" android:layout_width="match_parent">  
  8.         <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  9.             android:layout_width="wrap_content" android:text="TextView"  
  10.             android:layout_height="wrap_content" android:id="@+id/item_id" android:paddingRight="30dip"></TextView>  
  11.         <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  12.             android:layout_width="wrap_content" android:text="TextView"  
  13.             android:layout_height="wrap_content" android:id="@+id/item_status" android:paddingRight="30dip"></TextView>  
  14.         <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  15.             android:layout_width="wrap_content" android:text="TextView"  
  16.             android:layout_height="wrap_content" android:id="@+id/item_name"></TextView>  
  17.     </LinearLayout>  
  18.     <LinearLayout android:id="@+id/linearLayout2"  
  19.         android:layout_height="wrap_content" android:layout_width="match_parent">  
  20.         <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  21.             android:layout_width="wrap_content" android:text="TextView"  
  22.             android:layout_height="wrap_content" android:id="@+id/item_tool" android:paddingRight="30dip"></TextView>  
  23.         <TextView android:textAppearance="?android:attr/textAppearanceMedium"  
  24.             android:layout_width="wrap_content" android:text="TextView"  
  25.             android:layout_height="wrap_content" android:id="@+id/item_number"></TextView>  
  26.     </LinearLayout>  
  27.   
  28. </LinearLayout>  

好了,Json的数据处理我们也学习完了.

因为找不到比较好的文件服务器,如果哪位同学想要源码的,可以留邮件地址,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值