日期:2014-05-16 浏览次数:20439 次
public class Folk { String name; String career; String age; int salary; boolean sex;
public class MyJsonWriter { ArrayList<Folk> folks; File saveFile; public MyJsonWriter(ArrayList<Folk> folks){ this.folks=folks; } public void setFilePath(String filepath){ saveFile=new File(filepath); try { saveFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getJsonData(){ String jsonData = null; // String jsonData=new JSONStringer().object().key("village").value("abc").endObject().toString(); try { StringBuilder builder=new StringBuilder(); ArrayList<String> folksData=new ArrayList<String>(); JSONArray array=new JSONArray(); for(int i=0;i<folks.size();i++){ Folk folk=folks.get(i); JSONObject jsonObject=new JSONObject(); jsonObject.put("name", folk.getName()); jsonObject.put("sex", folk.isSex()?"male":"female"); jsonObject.put("age", folk.getAge()); jsonObject.put("career", folk.getCareer()); jsonObject.put("salary", folk.getSalary()); folksData.add(jsonObject.toString()); array.put(jsonObject); } // JSONArray jsonArray=new JSONArray(folksData); int len = array.length(); jsonData=new JSONStringer().object().key("vallage").value(array).endObject().toString(); System.out.println(jsonData); writeData(jsonData); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonData; } private void writeData(String jsonData) { // TODO Auto-generated method stub try { BufferedReader reader=new BufferedReader(new StringReader(jsonData)); BufferedWriter writer=new BufferedWriter(new FileWriter(saveFile)); int len=0; char[] buffer=new char[1024]; while((len=reader.read(buffer))!=-1){ writer.write(buffer, 0, len); } writer.flush(); writer.close(); reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class MyJsonReader { String jsonData; // ArrayList<Folk> folks; public MyJsonReader(String jsonData){ this.jsonData=jsonData; } public ArrayList<Folk> getJsonData(){ ArrayList<Folk> folks=new ArrayList<Folk>(); try { JSONObject jsonObject=new JSONObject(jsonData); JSONArray jsonArray=jsonObject.getJSONArray("vallage"); int len = jsonArray.length(); for(int i=0;i<jsonArray.length();i++){ JSONObject json=jsonArray.getJSONObject(i); Folk folk=new Folk(); folk.setName(json.optString("name")); folk.setAge(json.optString("age")); folk.setCareer(json.optString("career")); folk.setSalary(json.optInt("salary")); folk.setSex(json.optString("sex").equals("male")?true:false); folks.add(folk); } } catch (JSONException e) { // TO