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. 打断点效果如下:

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐