android中json數據的操作

一:保存json數據的操作

json的基本單元,主要包含一對(key/value)的值,與map的保存結構類似,是用{ }括起來的一組數據,如{key值,value值} ,{key值,[數值1,數值2,數值3]}

public class MainActivity extends Activity {

    private  String namedata[] = new String[]{"張三","李四"};
    private  int agedata[] = new int[]{20,21};
    private  int  salarydata[] = new int[]{5000,8000};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        JSONObject alldata = new JSONObject();//創建最外層的json對象,用於保存多個字符串信息
        JSONArray js = new JSONArray();//用於保存多個JSONObject對象
        for (int i = 0;i<namedata.length;i++){
            JSONObject temp = new JSONObject();//定義一個新的JSONObject
            try {
                temp.put("name",namedata[i]);//保存姓名進JSONObject
                temp.put("age",agedata[i]);
                temp.put("salary",salarydata[i]);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            js.put(temp);//保存JSONObject進JSONArray
        }
        try {
            alldata.put("personalData",js);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return;
        }

        File file = new File(Environment.getExternalStorageDirectory().toString()
        +File.separator+"myfile"+File.separator+"json.txt");
        if (!file.getParentFile().exists()){//父文件不存在
            file.getParentFile().mkdir();//創建文件夾
        }

        PrintStream out;
        try {
            out = new PrintStream(new FileOutputStream(file));
            out.print(alldata.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (out !=null){
                out.close();
            }
        }

    }
}



二:解析json數據


public class MainActivity extends Activity {

    private TextView msg = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.main);
        msg = (TextView)findViewById(R.id.msg);

        String str = "  { \"memberdata\": " +    //key值
                "[{\"id\":1,\"name\":李華,\"age\":30}," +//value值
                "{\"id\":2,\"name\":張三,\"age\":20}," +
                "{\"id\":3,\"name\":王五,\"age\":18}]," +
                "\"guet\":\"桂林電子科技大學\" }  ";  //guet是key值,桂林電子科技大學是value值

        StringBuffer buf = new StringBuffer();
        Map<String,Objects> result = null;//json解析函數
        try {
            result = parseJson(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        buf.append("學校名稱:" + result.get("guet") + "\n");//取出學校的信息
        List<Map<String,Objects>> alldata = (List<Map<String,Objects>>) result.get("memberdata");//取出memberdata結點裏面的數據並存入集合中
        Iterator<Map<String,Objects>> iter = alldata.iterator();//實例化

        while (iter.hasNext()){
            Map<String,Objects> map = iter.next();//從迭代器裏面取出每一對鍵值對
            buf.append("id"+map.get("id")+"姓名:"+map.get("name")+"年齡:"+map.get("age")+"\n");
        }
        msg.setText(buf);
    }


    public Map<String,Objects> parseJson(String str) throws  Exception{

        Map<String, String> allmap = new HashMap<>();

        JSONObject jsondata = new JSONObject(str); //定義JSONObject
        allmap.put("guet",jsondata.getString("guet"));

        JSONArray jsonarr =jsondata.getJSONArray("memberdata");
        List<Map<String,Objects>> all = new ArrayList<Map<String, Objects>>();
        for (int i = 0;i<jsonarr.length();i++){//取出數組中的每一個JSONObject
            Map<String, Integer> map = new HashMap<>();//保存每一組信息
            JSONObject jsonObj = jsonarr.getJSONObject(i);//取得每一個JSONObject
            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 null;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章