JSON > Java对象或集合

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.3</version>
</dependency>

<dependency>
    <groupId>com.colobu</groupId>
    <artifactId>fastjson-jaxrs-json-provider</artifactId>
    <version>0.3.1</version>
</dependency>
    //JSON转对象
    @Test
    public void JSONToJavaBean(){
    
    
        String json = "{\"age\":25,\"birthday\":\"2021-01-22 12:57:45\",\"username\":\"小斌\"}";
        //使用JSON对象的parseObject方法,将json转换为对象
        Person person = JSON.parseObject(json, Person.class);
        System.out.println(person);
        //Person(username=小斌, age=25, birthday=2021-01-22 12:57:45)
    }

    //JSON转集合
    @Test
    public void JSONToList(){
    
    
        String json = "[{\"USERNAME\":\"小斌\",\"AGE\":25},{\"USERNAME\":\"小斌\",\"AGE\":25},{\"USERNAME\":\"小斌\",\"AGE\":25}]";
        //视同JSON对象的parseArray方法,将json转换为集合
        List<Person> list = JSON.parseArray(json, Person.class);
        System.out.println(list);
        /*
            [
                Person(username=小斌, age=25, birthday=null),
                Person(username=小斌, age=25, birthday=null),
                Person(username=小斌, age=25, birthday=null)
            ]
         */
    }

猜你喜欢

转载自blog.csdn.net/kimyundung/article/details/113648468
今日推荐