JSON和對象集合之間的相互轉化

所需jar包:

<dependency>
            <groupId>com.hynnet</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.8.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

實例:

        //集合生成
        User user1 = new User("a","aa");
        User user2 = new User("b","bb");
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);

        //對象轉json
        JSONObject jsonObject = JSONObject.fromObject(user1);
        String str = jsonObject.toString();
        System.out.print(str);

       //json轉對象
        String JSONStr = JSON.toJSONString(str);
        User user = JSON.parseObject(str,new TypeReference<User>(){});


        //集合轉json字符串
        JSONArray json = JSONArray.fromObject(list);
        String str = json.toString();
        System.out.print(str);

        //json字符串轉集合
        String JSONStr = JSON.toJSONString(str);
        List<User> busLineList = JSON.parseObject(str,new TypeReference<List<User>>(){});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章