一、fastJson將json格式字符串轉(zhuǎn)化成List集合
注:json格式字符串必須符合數(shù)組型格式如[{"a":a},{"b":b}]
場(chǎng)景一:前端向后臺(tái)傳遞數(shù)組格式的json字符串,如何轉(zhuǎn)化成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);
//輸出測(cè)試
JsonUtils.beanToJson(readJson2List);
}
場(chǎng)景二:前端向后臺(tái)傳遞數(shù)組格式的json字符串,如何轉(zhuǎn)化成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);
//輸出測(cè)試
JsonUtils.beanToJson(readJson2List);
}
二、fastJson將json格式字符串轉(zhuǎn)化成對(duì)象
場(chǎng)景一:前端向后臺(tái)傳遞數(shù)組格式的json字符轉(zhuǎn)化成Bean對(duì)象
@Test
public void readJson2Bean() {
String json = "{"address": "address2","name":"haha2","id":2,"email":"email2"}";
AccountBean accountBean =JSON.parseObject(json,AccountBean.class);
//輸出測(cè)試
JsonUtils.beanToJson(accountBean);
}
場(chǎng)景二:前端向后臺(tái)傳遞數(shù)組格式的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);
//輸出測(cè)試
JsonUtils.beanToJson(accountBean);
}
測(cè)試:
三、FastJson將對(duì)象或集合轉(zhuǎn)化成json格式字符串
@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);
}
四、FastJson將json格式字符串轉(zhuǎn)化成json對(duì)象
@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);
}
五、FastJson將json格式字符串轉(zhuǎn)化成json數(shù)組
@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);
//輸出測(cè)試
JsonUtils.beanToJson(parseArray.get(0));
}
六、FastJson將java對(duì)象轉(zhuǎn)化成json對(duì)象
@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);
}
到此這篇關(guān)于Java工具庫(kù)FastJson使用詳解的文章就介紹到這了,更多相關(guān)Java其他工具庫(kù)的內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!