Gson
public class Demo_Gson {
public static void main(String[] args) {
//1、創建Gson物件
Gson g = new Gson();
//2、將物件轉換為JSON字串 String json = new Gson().toJSON(要轉換的物件);
Book b = new Book("1002","金蘋果","種蘋果");
String json = g.toJson(b);
System.out.println(json);
//3、將JSON字串轉換為物件 物件 = new Gson().fromJson(JSON字串,物件型別.class);
//Book b1 = g.fromJson(json,Book.class);
//轉換為Book物件
Book b1 = g.fromJson("{\"id\":\"1002\",\"name\":\"金蘋果\",\"info\":\"種蘋果\"}",Book.class);
System.out.println(b1.getId());
//轉換為Hashmap物件
HashMap data = g.fromJson("{\"id\":\"1002\",\"name\":\"金蘋果\",\"info\":\"種蘋果\"}",HashMap.class);
System.out.println(data.get("id"));
}
}

若JSON檔案中有陣列格式,轉換為物件時,陣列型別會變成ArrayList
public class Demo1 {
public static void main(String[] args) {
//1. 創建Gson物件
Gson g = new Gson();
//2. 將JSON字串轉換為物件 : {"id":"100","name":"金蘋果","info":"種植蘋果真辛苦","page":["鋤禾日當午","汗滴禾下土","嘿嘿嘿嘿嘿"]}
HashMap data = g.fromJson("{\"id\":\"100\",\"name\":\"金蘋果\",\"info\":\"種植蘋果真辛苦\",\"page\":[\"鋤禾日當午\",\"汗滴禾下土\",\"嘿嘿嘿嘿嘿\"]}", HashMap.class);
List page = (List) data.get("page");
System.out.println(data.get("page").getClass());
System.out.println(page.get(1));
}
}

FastJson
public class Demo_FastJson {
public static void main(String[] args) {
Book b = new Book("1002","金蘋果","種蘋果");
//將物件轉換為JSON字串 String json=JSON.toJSONString(要轉換的物件);
String json = JSON.toJSONString(b);
System.out.println(json);
//將JSON字串轉換為物件
//型別 物件名=JSON.parseObject(JSON字串, 型別.class)
Book b1 = JSON.parseObject("{\"id\":\"1002\",\"name\":\"金蘋果\",\"info\":\"種蘋果\"}",Book.class);
System.out.println(b1.getId());
//或List<型別> list=JSON.parseArray(JSON字串,型別.class)
List<String> list = JSON.parseArray("[\"鋤禾日當午\",\"汗滴禾下土\",\"嘿嘿嘿嘿嘿\"]",String.class);
System.out.println(list.get(1));
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/234906.html
標籤:其他
上一篇:window.open打開一個檔案地址,怎么修改檔案名
下一篇:Angular學習之核心檔案分析
