JSON解析 Gson的使用

JSON解析 Gson的使用

  • 数组

    • 数组转化为Json

      int[] numbers = {1, 1, 2, 3, 5, 8, 13};
      Gson gson = new Gson();
      String numbersJson = gson.toJson(numbers);      
      
    • json转化为数组

      int[] fibonacci = gson.fromJson(numbersJson, int[].class);
      for (int i = 0; i < fibonacci.length; i++) {
       System.out.print(fibonacci[i] + " ");
      }
      
  • 集合

    • 集合转化为Json

      List names = new ArrayList();
      names.add("Alice");
      names.add("Bob");
      names.add("Carol");
      names.add("Mallory");
      Gson gson = new Gson();
      String jsonNames = gson.toJson(names);
      System.out.println("jsonNames = " + jsonNames);
      
    • json转化为集合

      Type type = new TypeToken>(){}.getType();
      List studentList = gson.fromJson(jsonStudents, type);
      
      for (Student student : studentList) {
          System.out.println("student.getName() = " + student.getName());
      }
      
  • Map

    • Map转化为Json

      Map colours = new HashMap();
      colours.put("BLACK", "#000000");
      colours.put("RED", "#FF0000");
      colours.put("GREEN", "#008000");
      colours.put("BLUE", "#0000FF");
      colours.put("YELLOW", "#FFFF00");
      colours.put("WHITE", "#FFFFFF");
      Gson gson = new Gson();
      String json = gson.toJson(colours);
      System.out.println("json = " + json);
      
    • Json转化为Map

      Type type = new TypeToken>(){}.getType();
      Map map = gson.fromJson(json, type);
      for (String key : map.keySet()) {
          System.out.println("map.get = " + map.get(key));
      }
      
  • JavaBean

    • Bean类转化为Json

      Calendar dob = Calendar.getInstance();
      dob.set(2000, 1, 1, 0, 0, 0);
      Student student = new Student("Duke", "Menlo Park", dob.getTime());
      Gson gson = new Gson();
      String json = gson.toJson(student);
      
    • Json转化为Bean

      String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";
      Gson gson = new Gson();
      Student student = gson.fromJson(json, Student.class);
      

你可能感兴趣的:(Android)