fastJson 解析一个比较复杂的json串为Java对象
1.要解析的json串格式如下:[{"name": "慕容皝","users": [{"username": "50","house": { "address": "德茂地铁站"},"password": "123...
·
1.
要解析的json串格式如下:
[ { "name": "慕容皝", "users": [ { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" } ] }, { "name": "慕容龙城", "users": [ { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" } ] } ]
2. 不难发现: 本质是一个数组
数组里面有name属性和users属性,users属性又是一个数组,里面有两个个普通元素和一个引用元素,看似复杂的格式,只需要用
JSON.parseArray(content,UserGroup.class)
这一行代码就可以搞定
3.先创建JavaBean
4.目录结构
jsonString.txt 的内容如下:
[ { "name": "慕容皝", "users": [ { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" } ] }, { "name": "慕容龙城", "users": [ { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" }, { "username": "50", "house": { "address": "德茂地铁站"}, "password": "123456" } ] } ]
5. 测试方法:
public static void main(String[] args) throws IOException { File file = new File("F:\\project\\springboottest\\myspringboot\\src\\main\\java\\com\\example\\fastjsontest\\jsonString.txt"); Path path = file.toPath(); //用 Files 工具类将一个 文本转成字符串 读取 String content = new String(Files.readAllBytes(path)); List<UserGroup> userGroupList = JSON.parseArray(content,UserGroup.class); System.out.println(userGroupList); }
5. 打断点效果如下:
更多推荐
已为社区贡献2条内容
所有评论(0)