【JSON】数据解析

1、保存数组

View Code
public class MyJSONDemo extends Activity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.main);

        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

            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(); // 关闭输出

            }

        }

    }

}

2、复杂数据

View Code
public class MyJSONDemo extends Activity {

    private String nameData[] = new String[] { "李兴华", "魔乐科技", "MLDN" };

    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 = "北京魔乐科技软件学院(MLDN软件实训中心)" ;

    private String companyAddr = "北京市西城区美江大厦6层" ;

    private String companyTel = "010-51283346" ;



    @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 temp = new JSONObject(); // 每一个包装的数据都是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();

            }

            sing.put(temp); // 保存多个JSONObject

        }

        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(); // 关闭输出

            }

        }

    }

}


3、解析数组

View Code
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) ;

        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.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>>();

        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;

    }

}

4、复杂解析

View Code
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;

    }

}

 

 

你可能感兴趣的:(json)