1. 程式人生 > >FastJson中JsonArray、JsonObject、json格式字串、javabean之間相互轉化

FastJson中JsonArray、JsonObject、json格式字串、javabean之間相互轉化

package com.kenny; import java.awt.print.Book; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.SerializerFeature; import com.beltoo.customer.vo.BookVO; /** * 測試Json和javaBean之間的轉化 * @author kenny * */ public class TestJsonUtils { public static void main(String[] args) { // TODO Auto-generated method stub List<String> booktags = new ArrayList<>(); booktags.add("Philosophy"); booktags.add("History"); booktags.add("Psychology"); BookVO book = new BookVO(); book.setAuthor("wangyangming"); book.setBookcode("MS001"); book.setBookname("王陽明全集"); book.setBookprice(78.5); book.setBooktags(booktags); //javabean轉json格式的字串 String jsonObj = JSONObject.toJSONString(book); //fastjson預設不輸出值null的欄位,bookcode欄位就不會顯示出來, //但如果是book.setBooktype("")這種寫法也是會顯示的。 System.out.println(jsonObj); //但是加上SerializerFeature.WriteMapNullValue的話則會顯示null欄位booktype的。 String jsonObjInCludNull = JSONObject.toJSONString(book, SerializerFeature.WriteMapNullValue); System.out.println(jsonObjInCludNull); //顯示資料型別 //{"@type":"com.beltoo.customer.vo.BookVO","author":"wangyangming","bookcode":"MS001","bookname":"王陽明全集","bookprice":78.5D,"booktags":["Philosophy","History","Psychology"]} String jsonObjWithType = JSONObject.toJSONString(book,SerializerFeature.WriteClassName); System.out.println(jsonObjWithType); //json格式字串轉javabean
BookVO book1 = JSON.parseObject(jsonObj, BookVO.class); System.out.println(book1.getBookname()); //json格式字串轉javabean 跟用BookVO.class的方法是一樣的 BookVO book3 = JSON.parseObject(jsonObj, new TypeReference<BookVO>() {}); System.out.println("++++++++++"+book3.getBookname()+"++++++++"); //json格式字串轉化成JSONObject
JSONObject jobj = JSON.parseObject(jsonObj); System.out.println("**********"+jobj+"**********"); //json字串轉JsonArray 也就是反序列化 List<String> booktags2 = new ArrayList<>(); booktags2.add("文學"); booktags2.add("歷史"); booktags2.add("小說"); BookVO book2 = new BookVO(); book2.setAuthor("當年明月"); book2.setBookcode("MS002"); book2.setBookname("明朝那些事"); book2.setBookprice(198.0); book2.setBooktags(booktags2); List<BookVO> bookslist= new ArrayList<>(); bookslist.add(book); bookslist.add(book2); //JSONObject類是JSON類的子類,JSONObject的toJSONString方法其實是調JSON的方法,子類並沒有覆寫
String jsonArray = JSONObject.toJSONString(bookslist,SerializerFeature.WriteMapNullValue); System.out.println(jsonArray); JSONArray jsonarray = JSONArray.parseArray(jsonArray); for(int i = 0; i<jsonarray.size(); i++) { //經 驗證這樣是可以的 BookVO books = JSON.toJavaObject(jsonarray.getJSONObject(i), BookVO.class); System.out.println("---------"+books.getBookname()+"---------"); } } }