Java读写json

2017-01-13 19:13:22来源:CSDN作者:Al_assad人点击

Java读写json


实例用的json文件

  1. {"persons":[{"name":"Assad","home":"Guangzhou"},{"name":"John","home":"Shanghai"}]}

1、读取JSON对象
  1. public static void read(){
  2. //从.json文件读取json字符串
  3. StringBuilder jsonStr = new StringBuilder();
  4. try{
  5. BufferedReader reader = new BufferedReader(new FileReader(new File("test_create.json"))); //或者使用Scanner
  6. String temp = "";
  7. while((temp = reader.readLine())!= null)
  8. jsonStr.append(temp);
  9. reader.close();
  10. }catch (IOException ex){
  11. ex.printStackTrace();
  12. }
  13. //将json字符串转化为JSON对象,并读取内容
  14. try{
  15. JSONObject json = new JSONObject(jsonStr.toString());
  16. JSONArray jsonMembers = json.getJSONArray("persons");
  17. for(int i=0;i<jsonMembers.length();i++){
  18. JSONObject person = (JSONObject)jsonMembers.get(i);
  19. String name = (String)person.get("name"); //获取JSON对象的键值对
  20. String home = (String)person.get("home");
  21. System.out.println("name:"+name+"/nhome:"+home);
  22. }
  23. }catch(JSONException ex){
  24. ex.printStackTrace();
  25. }
  26. }

2、修改JSON对象
  1. public static void updateAndSave(){
  2. try{
  3. JSONObject json = new JSONObject("{/"persons/":[{/"name/":/"Assad/",/"home/":/"Guangzhou/"},{/"name/":/"John/",/"home/":/"Shanghai/"}]}");
  4. //增加JSON对象键值对
  5. JSONArray jsonMembers = json.getJSONArray("persons");
  6. JSONObject member3 = new JSONObject();
  7. member3.put("name","Time");
  8. member3.put("home","Beijing");
  9. jsonMembers.put(member3);
  10. //删除JSON对象键值对
  11. JSONObject member1 = (JSONObject) jsonMembers.get(0); //删除第一个成员的name字段
  12. member1.remove("name");
  13. System.out.println(json.toString()); //show
  14. }catch(JSONException ex){
  15. ex.printStackTrace();
  16. }
  17. }

3、创建JSON对象并保存为.json文件
  1. public static void create(){
  2. //创建JSON对象
  3. //①直接构造JSON对象
  4. JSONObject json = new JSONObject();
  5. try {
  6. JSONArray jsonMembers = new JSONArray(); //创建json数组
  7. JSONObject member1 = new JSONObject(); //创建空json对象
  8. member1.put("name","Assad"); //向json对象中放置键值对
  9. member1.put("home","Guangzhou");
  10. JSONObject member2 = new JSONObject();
  11. member2.put("name","John");
  12. member2.put("home","Shanghai");
  13. jsonMembers.put(member1);
  14. jsonMembers.put(member2);
  15. json.put("persons",jsonMembers);
  16. }catch(JSONException ex){
  17. ex.printStackTrace();
  18. }
  19. //②直接将Java对象转化为JSON对象
  20. Perosns persons= new Persons();
  21. JSONObject json = JSONObject.formObject(persons);*/
  22. //写入文件:将JSON对象转化为字符串后写入文件
  23. String jsonStr = json.toString(); //将JSON对象转化为字符串
  24. try{
  25. PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("test_create.json"))));
  26. writer.write(jsonStr);
  27. writer.close();
  28. }catch(IOException ex){
  29. ex.printStackTrace();
  30. }
  31. }



最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台