您好,登錄后才能下訂單哦!
這篇“Java工具庫FastJson如何使用”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Java工具庫FastJson如何使用”文章吧。
注:json格式字符串必須符合數組型格式如[{"a":a},{"b":b}]
場景一:前端向后臺傳遞數組格式的json字符串,如何轉化成List集合
List<AccountBean> readJson2List =JSON.parseArray(json, AccountBean.class)注意這里是Bean.class而不是List.class
@Test
public void readJson2ListBean() {
String json = "[{"address": "address2","name":"haha2","id":2,"email":"email2"},{"address":"address","name":"haha","id":1,"email":"email"}]";
List<AccountBean> readJson2List =JSON.parseArray(json, AccountBean.class);
//輸出測試
JsonUtils.beanToJson(readJson2List);
}
場景二:前端向后臺傳遞數組格式的json字符串,如何轉化成List<HashMap<String,Object>>集合
@Test
public void readJson2ListMap() {
String json = "[{"address": "address2","name":"haha2","id":2,"email":"email2"},{"address":"address","name":"haha","id":1,"email":"email"}]";
List<HashMap> readJson2List =JSON.parseArray(json,HashMap.class);
//輸出測試
JsonUtils.beanToJson(readJson2List);
}
場景一:前端向后臺傳遞數組格式的json字符轉化成Bean對象
@Test
public void readJson2Bean() {
String json = "{"address": "address2","name":"haha2","id":2,"email":"email2"}";
AccountBean accountBean =JSON.parseObject(json,AccountBean.class);
//輸出測試
JsonUtils.beanToJson(accountBean);
}
場景二:前端向后臺傳遞數組格式的json字符串Map<String,Object>集合
@Test
public void readJson2Map() {
String json = "{"address": "address2","name":"haha2","id":2,"email":"email2"}";
HashMap<String,Object> accountBean =JSON.parseObject(json,Map.class);
//輸出測試
JsonUtils.beanToJson(accountBean);
}
@Test
public void beanAndCollectionTOJson() {
AccountBean bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("hoojo_@126.com");
bean.setId(1);
bean.setName("hoojo");
String json = JSON.toJSONString(bean);
System.out.println(json);
}
@Test
public void jsonStringTOJsonBean() {
String json = "{"address": "address2","name":"haha2","id":2,"email":"email2"}";
JSONObject parse = (JSONObject) JSON.parse(json);
String address = (String) parse.get("address");
System.out.println("輸出address=="+address);
}
@Test
public void jsonString2JsonArray() {
String json = "[{"address": "address2","name":"haha2","id":2,"email":"email2"},{"address":"address","name":"haha","id":1,"email":"email"}]";
JSONArray parseArray = JSON.parseArray(json);
//輸出測試
JsonUtils.beanToJson(parseArray.get(0));
}
@Test
public void beanAndCollectionTOJsonBean() {
AccountBean bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("hoojo_@126.com");
bean.setId(1);
bean.setName("hoojo");
JSONObject json = (JSONObject) JSON.toJSON(bean);
json.get("address");
System.out.println(json);
}
以上就是關于“Java工具庫FastJson如何使用”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。