您好,登录后才能下订单哦!
这篇“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。