By GokiSoft.com| 15:24 20/04/2020|
Java Advanced

Share Code - JSON - Thông tin lớp học bằng Java

Source Code Bài giảng - JSON - Java

Download thư viện JSON tại link sau => https://mvnrepository.com/artifact/org.json/json/20190722

JSON File

[
	{
		"classname": "T1907A",
		"address": "8 Ton That Thuyet, Cau Giay, HN",
		"teacher": {
			"fullname": "Tran Van A",
			"age": 32,
			"address": "Nam Dinh"
		},
		"student_list": [
			{
				"fullname": "Tran Van A",
				"age": 19,
				"address": "Ha Noi"
			},
			{
				"fullname": "Tran Van A",
				"age": 19,
				"address": "Ha Noi"
			}
		]
	},
	{
		"classname": "T1907E",
		"address": "8 Ton That Thuyet, Cau Giay, HN",
		"teacher": {
			"fullname": "Tran Van B",
			"age": 32,
			"address": "Nam Dinh"
		},
		"student_list": [
			{
				"fullname": "Tran Van B",
				"age": 19,
				"address": "Ha Noi"
			},
			{
				"fullname": "Tran Van B",
				"age": 19,
				"address": "Ha Noi"
			}
		]
	}
]

Aptech Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession3;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Diep.Tran
 */
public class AptechClass {
    String classname,   address;
    Teacher teacher;
    List<Student> student_list;

    public AptechClass() {
        student_list = new ArrayList<>();
        teacher = new Teacher();
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public List<Student> getStudent_list() {
        return student_list;
    }

    public void setStudent_list(List<Student> student_list) {
        this.student_list = student_list;
    }
    
    public void convertJSON(JSONObject obj) {
        classname = obj.getString("classname");
        address = obj.getString("address");
        
        JSONObject teacherObj = obj.getJSONObject("teacher");
        teacher.convertJSON(teacherObj);
        
        JSONArray arr = obj.getJSONArray("student_list");
        for (int i = 0; i < arr.length(); i++) {
            JSONObject stdObj = arr.getJSONObject(i);
            
            Student std = new Student();
            std.convertJSON(stdObj);
            
            student_list.add(std);
        }
    }
    
    public void display() {
        System.out.println("ClassName: " + classname + ", Address: " + address);
        System.out.println(teacher);
        for (Student student : student_list) {
            System.out.println(student);
        }
    }
}


Student Class
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession3;

import org.json.JSONObject;

/**
 *
 * @author Diep.Tran
 */
public class Student {
    String fullname, address;
    int age;

    public Student() {
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    public void convertJSON(JSONObject obj) {
        fullname = obj.getString("fullname");
        address = obj.getString("address");
        age = obj.getInt("age");
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", address=" + address + ", age=" + age + '}';
    }
    
    
}

Teacher Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession3;

import org.json.JSONObject;

/**
 *
 * @author Diep.Tran
 */
public class Teacher {
    String fullname, address;
    int age;

    public Teacher() {
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    public void convertJSON(JSONObject obj) {
        fullname = obj.getString("fullname");
        address = obj.getString("address");
        age = obj.getInt("age");
    }

    @Override
    public String toString() {
        return "Teacher{" + "fullname=" + fullname + ", address=" + address + ", age=" + age + '}';
    }
    
    
}

Main Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession3;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //Vi du: chuyen doi json file toi class object
        FileInputStream fis = null;
        
        try {
            //Step 1: doc content tu file json.
            fis = new FileInputStream("student.json");
            
            StringBuilder builder = new StringBuilder();
            int code;
            
            while((code = fis.read()) != -1) {
                builder.append((char) code);
            }
            
            String content = builder.toString();
            //Step 2: Convert du lieu tu JSON to class object
            JSONArray array = new JSONArray(content);
            
            List<AptechClass> aptechClassList = new ArrayList<>();
            
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                
                AptechClass aptechClass = new AptechClass();
                aptechClass.convertJSON(obj);
                
                aptechClassList.add(aptechClass);
            }
            
            for (AptechClass aptechClass : aptechClassList) {
                aptechClass.display();
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}



Tóm lại kiến thức môn XML/JSON
- XML
	=> Gửi data: Client & Server
		=> SOAP API => rộng rãi
		=> ...
	=> Setting (Config) => trong apps (Netbean, ...)
	=> UI (Java FX, Android, ...)

- JSON
	=> Gửi data
		=> Client & Server: JSON
		=> Refull API.

XML & JSON
- Ưu điểm JSON
	=> Dữ liệu nhỏ hơn XML rất nhiều
	=> Convert JSON string to object (array) => Java, PHP, JS,... nó rất dễ.

* JSON
	=> Cách tạo file JSON
	=> Cách ứng dụng file JSON trong project
		=> JS => qua dễ rồi. JSON.parse xong, object => json 	=> JSON.stringify => JS
		=> Java
			=> JSON => convert => class object
			=> class object => convert => JSON string

			Step by step (JSON thuong)
			=> Mapping json => class object
			=> Doc dc noi dung trong file json
			=> Convert du lieu tu JSON to class object


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

NguyenHuuThanh [T1907A]
NguyenHuuThanh

2020-04-22 03:07:54





/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jsonfile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;


/**
 *
 * @author abc
 */
public class Main {
    public static void main(String[] args)
    {
        // Chuyển đổi json file -> class object
        FileInputStream fis = null ;
        // STEP 1 : DOC CONTENT
        try
        {
            // DOC CONTENT TU FILE JSON :
            
            fis = new FileInputStream("student01.json");
            
            StringBuilder builder = new StringBuilder();
            // DOC TUNG KY TU MOT
            int code ;
            
            while ((code = fis.read()) != -1 )
            {
                builder.append((char) code );
            }
            // LAY NOI DUNG :
            String content = builder.toString();
            
            // STEP 2 : CONVERT du lieu tu json -> class object
            // CHUỖI JSON ĐÃ CÓ SẴN . NẾU TRÊN MẠNG THÌ PHẢI LẤY API
            JSONArray array = new JSONArray(content);
            
            List<AptechClass> aptechClassList = new ArrayList<>();
            
            for ( int i = 0 ; i < array.length() ; i++)
            {
                JSONObject obj = array.getJSONObject(i);
                
                AptechClass aptechClass = new AptechClass();
                aptechClass.convertJSON(obj);
                
                aptechClassList.add(aptechClass);
                
            }
            
            for (AptechClass aptechClass : aptechClassList)
            {
                aptechClass.display();
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if (fis != null)
            {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
        
    
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jsonfile;

import org.json.JSONObject;

/**
 *
 * @author abc
 */
public class Teacher {
    String fullname , address ;
    int age ;
    
    public Teacher()
    {
        
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" + "fullname=" + fullname + ", address=" + address + ", age=" + age + '}';
    }
    
    public void convertJSON(JSONObject obj)
    {
        fullname = obj.getString("fullname");
        address = obj.getString("address");
        age = obj.getInt("age");
    }
    
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jsonfile;

import org.json.JSONObject;

/**
 *
 * @author abc
 */
public class Student {
    String fullname  , address ;
    int age;
    
    public Student()
    {
        
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", address=" + address + ", age=" + age + '}';
    }
    
    public void convertJSON(JSONObject obj)
    {
        fullname = obj.getString("fullname");
        address  = obj.getString("address");
        age      = obj.getInt("age");
    }
    
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jsonfile;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author abc
 */
public class AptechClass {
    String classname , address ;
    Teacher teacher ;
    List<Student> student_list;
    
    public AptechClass()
    {
        student_list = new ArrayList<>();
        teacher = new Teacher();
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public List<Student> getStudent_list() {
        return student_list;
    }

    public void setStudent_list(List<Student> student_list) {
        this.student_list = student_list;
    }
    
    public void convertJSON(JSONObject obj)
    {
        classname = obj.getString("classname");
        address = obj.getString("address");
        
        JSONObject teacherObj = obj.getJSONObject("teacher");
        
        JSONArray arr = obj.getJSONArray("student_list");
        
        for ( int i = 0 ; i < arr.length() ; i++)
        {
            JSONObject stdObj = arr.getJSONObject(i);
            
            Student std = new Student();
            std.convertJSON(stdObj);
            
            student_list.add(std);
        }
        
    }
    
    public void display()
    {
        System.out.println("ClassName :" + classname);
        System.out.println(teacher);
        for (Student student : student_list)
        {
            System.out.println(student);
        }
    }
    
    
    
}