By GokiSoft.com|
20:12 21/09/2021|
Java Advanced
[Share Code] Tìm hiểu JSON - GSon Lập trình Java nâng cao
#aptech.json
[
{
"name": "SEM1",
"subject-list": [
{
"name": "Lap Trinh C",
"price": 200000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "Lap Trinh HTML/CSS/JS",
"price": 100000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "SQL Server",
"price": 300000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
}
]
},
{
"name": "SEM2",
"subject-list": [
{
"name": "ADF1",
"price": 200000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "ADF2",
"price": 100000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "XML/JSON",
"price": 300000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
}
]
}
]
#book-list.json
[
{
"name": "Lap Trinh C",
"price": 200000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "Lap Trinh HTML/CSS/JS",
"price": 100000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
},
{
"name": "SQL Server",
"price": 300000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
}
]
#book.json
{
"name": "Lap Trinh C",
"price": 200000,
"authorName": "TRAN VAN DIEP",
"manufacturer": "Aptech"
}
#Book.java
/*
* 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 xml.lesson03;
import org.json.JSONObject;
/**
*
* @author Diep.Tran
*/
public class Book {
String name;
int price;
String authorName;
String manufacturer;
public Book() {
}
public Book(String name, int price, String authorName, String manufacturer) {
this.name = name;
this.price = price;
this.authorName = authorName;
this.manufacturer = manufacturer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
@Override
public String toString() {
return "Book{" + "name=" + name + ", price=" + price + ", authorName=" + authorName + ", manufacturer=" + manufacturer + '}';
}
public void parseJSON(JSONObject obj) {
this.name = obj.getString("name");
this.price = obj.getInt("price");
this.authorName = obj.getString("authorName");
this.manufacturer = obj.getString("manufacturer");
}
}
#GsonTest.java
/*
* 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 xml.lesson03;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
/**
*
* @author Diep.Tran
*/
public class GsonTest {
public static void main(String[] args) {
//parseGson1();
//parseGson2();
parseGson3();
}
static void parseGson1() {
String content = Utility.getContentFromFile("book.json");
Gson gson = new Gson();
Book b = gson.fromJson(content, Book.class);
System.out.println(b);
}
static void parseGson2() {
String content = Utility.getContentFromFile("book-list.json");
Gson gson = new Gson();
List<Book> dataList = gson.fromJson(content, new TypeToken<List<Book>>(){}.getType());
dataList.forEach(book -> {
System.out.println(book);
});
}
static void parseGson3() {
String content = Utility.getContentFromFile("aptech.json");
Gson gson = new Gson();
List<Semester> dataList = gson.fromJson(content, new TypeToken<List<Semester>>(){}.getType());
dataList.forEach(semester -> {
semester.display();
});
Semester semester = new Semester();
semester.setName("SEM3");
semester.getBookList().add(new Book("WinForm", 150000, "TRAN VAN A", "APTECH"));
dataList.add(semester);
//Save list -> json
String json = gson.toJson(dataList);
Utility.saveFile(json, "aptech01.json");
}
}
#Main.java
/*
* 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 xml.lesson03;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author Diep.Tran
*/
public class Main {
public static void main(String[] args) {
parseJSON2();
}
static void parseJSON1() {
String content = Utility.getContentFromFile("book.json");
JSONObject obj = new JSONObject(content);
Book b = new Book();
b.parseJSON(obj);
System.out.println(b);
}
static void parseJSON2() {
String content = Utility.getContentFromFile("book-list.json");
List<Book> dataList = new ArrayList<>();
JSONArray arr = new JSONArray(content);
for(int i=0;i<arr.length();i++) {
JSONObject obj = arr.getJSONObject(i);
Book b = new Book();
b.parseJSON(obj);
dataList.add(b);
}
for (Book book : dataList) {
System.out.println(book);
}
}
}
#Semester.java
/*
* 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 xml.lesson03;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Diep.Tran
*/
public class Semester {
String name;
@SerializedName("subject-list")
List<Book> bookList;
public Semester() {
bookList = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
public void display() {
System.out.println("Thong tin ky hoc");
System.out.println("Ky hoc: " + name);
bookList.forEach(book -> {
System.out.println(book);
});
}
}
#Utility.java
/*
* 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 xml.lesson03;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class Utility {
public static String getContentFromFile(String filename) {
StringBuilder builder = new StringBuilder();
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader(filename);
bufferedReader = new BufferedReader(reader);
String line = "";
while((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return builder.toString();
}
public static void saveFile(String content, String filename) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
byte[] data = content.getBytes("utf8");
fos.write(data);
} catch (FileNotFoundException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)