解析JSON
- Gson: Java Bean => JSON String
- fastjson:解析JSON String
1> jar包獲取
- fastjson-1.2.68.jar
- gson-2.8.6.jar
https://download.csdn.net/download/qq_42292831/12438540
2> 測試
- Market對象
Market m1 = new Market();
Book book1 = new Book("《時間簡史》",89.9);
Book book2 = new Book("《大學物理》",35.5);
List<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
m1.setBooks(books);
List<Market> markets = new ArrayList<>();
for(int i=0;i<2;i++){
markets.add(m1);
}
- GSON將bean轉換爲JSON串
//GSON將bean轉換爲JSON串
//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(markets);
- fastjson解析JSON串
//fastjson解析JSON串
//JSONArray
//JSONObject
JSONArray objs = JSON.parseArray(json);
for(int i=0;i<objs.size();i++){
JSONObject marketsA = objs.getJSONObject(i);
JSONArray booksA = marketsA.getJSONArray("Books");
for(int j=0;j<booksA.size();j++){
JSONObject bookA = booksA.getJSONObject(j);
System.out.println(bookA.get("name"));
System.out.println(bookA.get("price"));
}
}