Java基础之FastJson详解
程序员文章站
2022-03-17 22:17:49
一、fastjson将json格式字符串转化成list集合注:json格式字符串必须符合数组型格式如[{"a":a},{"b":b}]场景一:前端向后台传递数组格式的json字符串,如何转化成list...
一、fastjson将json格式字符串转化成list集合
注: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); }
二、fastjson将json格式字符串转化成对象
场景一:前端向后台传递数组格式的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); }
测试:
三、fastjson将对象或集合转化成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格式字符串转化成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); }
五、fastjson将json格式字符串转化成json数组
@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)); }
六、fastjson将java对象转化成json对象
@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详解的文章就介绍到这了,更多相关java fastjson内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!