Android数据存储——2.文件存储_F_解析JSON文档

今天学习Android数据存储——文件存储_解析JSON文档 

    
    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

    JSON建构有两种结构:
    json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组2种结构,通过这两种结构可以表示各种复杂的结构
1、对象(JSONObject):对象在js中表示为“{}”扩起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。
2、数组(JSONArray):数组在js中是中括号“[]”扩起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。
经过对象、数组2种结构就可以组合成复杂的数据结构了。

JSON解析的操作类
JSON Object类的常用方法

实例:用JSON文件保存简单数组
Java代码:
public class MyJSONDemo extends Activity {  
protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        super.setContentView(R.layout.main);  
        /** 
         * 用JSON文件保存数组 
         */  
        String data[] = new String[]{"www.mldnjava.cn","lixinghua","bbs.mldn.cn"};//要输出的数据  
        JSONObject allData = new JSONObject();//建立最外面的节点对象  
        JSONArray sing = new JSONArray();//定义数组  
        for(int x = 0;x<data.length;x++){//将数组内容配置到相应的节点  
            JSONObject temp = new JSONObject();//JSONObject包装数据,而JSONArray包含多个JSONObject  
            try {  
                temp.put("myurl", data[x]); //JSONObject是按照key:value形式保存  
            } catch (JSONException e) {  
                e.printStackTrace();  
            }  
            sing.put(temp);//保存多个JSONObject  
        }  
        try {  
            allData.put("urldata", sing);//把JSONArray用最外面JSONObject包装起来  
        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
        if(!Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED)){//SD卡不存在则不操作  
            return;//返回到程序的被调用处   
        }  
        File file = new File(Environment.getExternalStorageDirectory()  
                +File.separator+"mldndata"+File.separator  
                +"json.txt");//要输出的文件路径  
        if(!file.getParentFile().exists()){//文件不存在  
            file.getParentFile().mkdirs();//创建文件夹  
        }  
        PrintStream out = null;  
        try {  
            out = new PrintStream(new FileOutputStream(file));  
            out.print(allData.toString());//将数据变为字符串后保存  
        }   
        catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
        finally{  
            if(out!=null){  
                out.close();//关闭输出  
            }  
        }  
    }  
}
json.txt内容:
json.txt内容分析:


实例:用JSON文件保存复杂数据
Java代码:
public class MyJSONDemo extends Activity {  
    private String nameData[] = new String[]{"李兴华","魔乐科技","MLDN"};  
    private int ageData[] = new int[]{30,5,7};  
    private boolean isMarriedData[] = new boolean[]{false,true,false};  
    private double salaryData[] = new double[]{3000.0,5000.0,9000.0};  
    private Date birthdayData[] = new Date[]{new Date(),new Date(),new Date()};  
      
    private String companyName = "北京魔乐科技软件学院(MLDN软件实训中心)";  
    private String companyAddr = "北京市西城区美江大厦6层";  
    private String companyTel = "010-51283346";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	super.setContentView(R.layout.main);  
        /** 
         * 用JSON文件保存复杂数据 
         */  
        JSONObject allData = new JSONObject();//建立最外面的节点对象  
        JSONArray sing = new JSONArray();//定义数组  
          
        for(int x = 0; x < this.nameData.length; x++){//将数组内容配置到相应的节点  
            JSONObject temp = new JSONObject();//JSONObject包装数据,而JSONArray包含多个JSONObject  
            try {  
                //每个JSONObject中,后加入的数据显示在前面  
                temp.put("name", this.nameData[x]);  
                temp.put("age", this.ageData[x]);  
                temp.put("married", this.isMarriedData[x]);  
                temp.put("salary", this.salaryData[x]);  
                temp.put("birthday", this.birthdayData[x]);  
                //JSONObject是按照key:value形式保存  
            } catch (JSONException e) {  
                e.printStackTrace();  
            }  
            sing.put(temp);//保存多个JSONObject  
        }  
        try {  
            allData.put("persondata", sing);//把JSONArray用最外面JSONObject包装起来  
            allData.put("company",this.companyName);  
            allData.put("address",this.companyAddr);  
            allData.put("telephone",this.companyTel);  
        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
        if(!Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED)){//SD卡不存在则不操作  
            return;//返回到程序的被调用处   
        }  
        File file = new File(Environment.getExternalStorageDirectory()  
                +File.separator+"mldndata"+File.separator  
                +"json.txt");//要输出的文件路径  
        if(!file.getParentFile().exists()){//文件不存在  
            file.getParentFile().mkdirs();//创建文件夹  
        }  
        PrintStream out = null;  
        try {  
            out = new PrintStream(new FileOutputStream(file));  
            out.print(allData.toString());//将数据变为字符串后保存  
        }   
        catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
        finally{  
            if(out!=null){  
                out.close();//关闭输出  
            }  
        }  
    }
} 
json.txt内容:

实例:解析JSON文件的简单数组
XML布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MyJSONDemo" >
    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>
Java代码:
public class MyJSONDemo extends Activity {  
    private TextView msg = null;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        super.setContentView(R.layout.main);  
          
        this.msg=(TextView)super.findViewById(R.id.msg);  
	  String str = "[{\"id\":1,\"name\":\"李兴华\",\"age\":30},"  
            		+"{\"id\":2,\"name\":\"MLDN\",\"age\":10}]";  
        StringBuffer buf = new StringBuffer();  
          
        try {  
            List<Map<String, Object>> all = this.parseJson(str);  
            Iterator<Map<String, Object>> iter = all.listIterator();//迭代器遍历List集合   
            while(iter.hasNext()){  
                Map<String, Object> map = iter.next();  
                buf.append("ID:"+map.get("id")+", 姓名:"+map.get("name")+", 年龄:"+map.get("age")+"\n");  
            }  
              
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        this.msg.setText(buf);  
    }
    /** 
     * 解析JSON文件的简单数组 
      */  
    private List<Map<String, Object>> parseJson(String data) throws Exception{  
        List<Map<String, Object>> all = new ArrayList<Map<String,Object>>();  
        JSONArray jsonArr = new JSONArray(data);    //是数组   
        for(int x= 0;x<jsonArr.length();x++){  
            Map<String, Object> map = new HashMap<String, Object>();  
            JSONObject jsonobj = jsonArr.getJSONObject(x);  
            map.put("id", jsonobj.getInt("id"));  
            map.put("name", jsonobj.getString("name"));  
            map.put("age", jsonobj.getInt("age"));  
            all.add(map);  
        }  
        return all;  
    }  
} 

解析结果:

实例:解析复杂JSON文件
Java代码:
public class MyJSONDemo extends Activity {  
    private TextView msg = null;  
      
    @SuppressWarnings("unchecked")  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        super.setContentView(R.layout.main);  
          
        this.msg=(TextView)super.findViewById(R.id.msg);  
	  String str = "{\"memberdata\":[{\"id\":1,\"name\":\"李兴华\",\"age\":30},"  
                	+"{\"id\":2,\"name\":\"MLDN\",\"age\":10}],\"company\":\"北京魔乐科技软件学院\"}";  
        StringBuffer buf = new StringBuffer();  
        try {  
            Map<String, Object> result = this.parseJson(str);//解析文本   
            buf.append("公司名称:"+result.get("company")+"\n");  
            List<Map<String, Object>> all = (List<Map<String,Object>>)result.get("memberdata");  
            Iterator<Map<String, Object>> iter = all.listIterator();//迭代器遍历List集合   
            while(iter.hasNext()){  
                Map<String, Object> map = iter.next();  
                buf.append("ID:"+map.get("id")+", 姓名:"+map.get("name")+", 年龄:"+map.get("age")+"\n");  
            }  
              
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        this.msg.setText(buf);  
    }  
    /** 
     * 解析复杂JSON文件 
     */  
    private Map<String, Object> parseJson(String data) throws Exception{  
        Map<String, Object> allMap = new HashMap<String,Object>();  
        JSONObject allData = new JSONObject(data);  //全部内容变为一个项   
        allMap.put("company", allData.getString("company"));    //取出项   
        JSONArray jsonArr = allData.getJSONArray("memberdata"); //取出数组   
        List<Map<String, Object>> all =new ArrayList<Map<String,Object>>();  
        for(int x= 0;x<jsonArr.length();x++){  
            Map<String, Object> map = new HashMap<String, Object>();  
            JSONObject jsonobj = jsonArr.getJSONObject(x);  
            map.put("id", jsonobj.getInt("id"));  
            map.put("name", jsonobj.getString("name"));  
            map.put("age", jsonobj.getInt("age"));  
            all.add(map);  
        }  
        allMap.put("memberdata", all);  
        return allMap;  
    }  
}  
解析结果:




posted @ 2013-04-17 17:26  魅惑之眼  阅读(206)  评论(0编辑  收藏  举报