thieumao

JSON demo

Nov 14th, 2013
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package com.blogspot.code4lifevn.json;
  2.  
  3. import org.json.simple.JSONArray;
  4. import org.json.simple.JSONObject;
  5. import org.json.simple.parser.JSONParser;
  6. import org.json.simple.parser.ParseException;
  7.  
  8. public class Main {
  9.  
  10.     public static void main(String[] args) {
  11.  
  12.         // Chuỗi JSON mẫu mô tả một danh sách các đối tượng Student
  13.         String jsonString = "[{\"id\": \"1\", \"name\": \"Duy hung\", \"email\": \"[email protected]\"}, {\"id\": \"2\", \"name\": \"Do manh\", \"email\": \"[email protected]\"}, {\"id\": \"3\", \"name\": \"Thai trung\", \"email\": \"[email protected]\"} ]";
  14.  
  15.         // Phân tích
  16.         try {
  17.  
  18.             // 1. Tạo ra một JSONParser
  19.             JSONParser jsonParser = new JSONParser();
  20.  
  21.             // 2. Parser chuỗi JSON về một JSONArray
  22.             JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonString);
  23.  
  24.             // 3. Lấy các giá trị trong jsonArray bằng cách lặp qa từng phần tử
  25.             for (int i = 0; i < jsonArray.size(); i++) {
  26.  
  27.                 // Mỗi phần tử của JSONArray lại là một JSONObject
  28.                 JSONObject jsonObject = (JSONObject) jsonArray.get(i);
  29.  
  30.                 int id = Integer.parseInt((String) jsonObject.get("id"));
  31.                 String name = (String) jsonObject.get("name");
  32.                 String email = (String) jsonObject.get("email");
  33.  
  34.                 // Gán vào đối tượng và in ra màn hình
  35.                 Student student = new Student(id, name, email);
  36.                 System.out.println("ID    : " + student.getId());
  37.                 System.out.println("Name  : " + student.getName());
  38.                 System.out.println("Email : " + student.getEmail());
  39.                 System.out.println();
  40.             }
  41.  
  42.         } catch (ParseException e) {
  43.             e.printStackTrace();
  44.         }
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment