• 【数据存储】JSON数据解析


     

    定义SD操作权限

     

    <uses-permission 
            android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

     

     

     

    范例: JSONProject(保存数组)

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    
    public class MyJSONDemo extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.main);
            // 要输出的数据
            String data[] = new String[] { 
                    "www.baidu.com", "baidu",
                    "www.google.com.hk" }; 
            // 建立最外面的节点对象
            JSONObject allData = new JSONObject(); 
            // 定义数组
            JSONArray sing = new JSONArray(); 
            // 将数组内容配置到相应的节点
            for (int x = 0; x < data.length; x++) { 
                // 每一个包装的数据都是JSONObject
                JSONObject temp = new JSONObject(); 
                try {
                    temp.put("myurl", data[x]);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sing.put(temp); // 保存多个JSONObject
            }
            try {
                allData.put("urldata", sing);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (!Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) { // 不存在不操作
                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(); 
                }
            }
        }
    }
    View Code

    范例:JSONProject(复杂数据)

    本次操作保存的数据如下:

       1)一个外部的JSONObject(要保存多个字符串信息,包括name,address,telephone

         和一个JSONArray对象。

       2)一个JSONArray对象中,要保存多个JSONObject

       3)每一个保存在JSONArray对象中的JSONObject对象都要保存多种数据类型

        (int,boolean等)。

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.util.Date;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    
    public class MyJSONDemo extends Activity {
        private String nameData[] = new String[] 
                { "李XX", "魔XXX", "BEYOND" };
        private int ageData[] = new int[] { 30, 5, 7 };
        private boolean isMarraiedData[] = 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 = "北京乌拉乌拉乌拉乌拉" ;
        private String companyAddr = "深圳拉拉拉拉阿拉拉拉啦" ;
        private String companyTel = "029837363535343" ;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.main);
            // 建立最外面的节点对象
            JSONObject allData = new JSONObject(); 
            // 定义数组
            JSONArray sing = new JSONArray(); 
            // 将数组内容配置到相应的节点
            for (int x = 0; x < this.nameData.length; x++) { 
                // 每一个包装的数据都是JSONObject
                JSONObject temp = new JSONObject(); 
                try {
                    temp.put("name", this.nameData[x]);
                    temp.put("age", this.ageData[x]);
                    temp.put("married", this.isMarraiedData[x]);
                    temp.put("salary", this.salaryData[x]);
                    temp.put("birthday", this.birthdayData[x]);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 保存多个JSONObject
                sing.put(temp); 
            }
            try {
                allData.put("persondata", sing);
                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)) { // 不存在不操作
                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(); 
                }
            }
        }
    }
    View Code

    范例:JSONProject(解析数组)

    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 android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class MyJSONDemo extends Activity {
        private TextView msg = null ;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.main);
            this.msg = (TextView) super.findViewById(R.id.msg) ;
            // 定义JSON数据
            String str = "[{\"id\":1,\"name\":\"李兴华\",\"age\":30},"
                    + "{\"id\":2,\"name\":\"MLDN\",\"age\":10}]";
            // 保存数据
            StringBuffer buf = new StringBuffer() ;
            try {
                // 解析JSON文本
                List<Map<String,Object>> all = this.parseJson(str) ;
                // 实例化Iterator
                Iterator<Map<String,Object>> iter = all.iterator() ;
                // 迭代输出
                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) ;// 设置显示文本
        }
        private List<Map<String, Object>> parseJson(String data) 
          throws Exception {
            List<Map<String, Object>> all = 
                           new ArrayList<Map<String, Object>>();
            // 定义JSON数组
            JSONArray jsonArr = new JSONArray(data); // 是数组
            // 取出数组中的JSONObject
            for (int x = 0; x < jsonArr.length(); x++) {
                // 保存信息
                Map<String, Object> map = new HashMap<String, Object>();
                // 取得每一个JSONObject
                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;
        }
    }
    View Code

    范例:JSONProject(复杂解析)

    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 android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class MyJSONDemo extends Activity {
        private TextView msg = null ;
    
        @SuppressWarnings("unchecked")
        @Override
        public 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.iterator() ;
                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) ;
        }
    
        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;
        }
    }
    View Code

  • 相关阅读:
    Python课程回顾(day26)网络编程
    Python课程回顾(day27)
    Python课程回顾(day25)
    Python课程回顾(day24)
    Python课程回顾(day23)
    Python课程回顾(day22)
    Python课程回顾(day21)
    Python课程回顾(day20)
    Python课程回顾(day19)
    hive小tips(各种解析)
  • 原文地址:https://www.cnblogs.com/androidsj/p/3129227.html
Copyright © 2020-2023  润新知