JSON轉化為對象

來源:互聯網
上載者:User

標籤:span   關鍵字   warning   log   對象   print   技術分享   png   target   

之前寫過對象轉化為JSON,http://www.cnblogs.com/loger1995/p/6613488.html

現在來寫寫JSON轉化為對象的方法,以及需要注意的地方!

 

導包:

這些包通過百度關鍵字:JSONObject所必須的6個包 即可找到!

 

建立一個測試類別:

package com.loger.test;import java.util.ArrayList;import java.util.List;import org.junit.Test;import com.loger.bean.User;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import net.sf.json.JsonConfig;public class TestJSON {        public static List<User> list = new ArrayList<>();    static {        list.add(new User("陳樂","21"));        list.add(new User("張卓鵬","20"));    }        /*     * 測試JSONArray 轉  List     */    @SuppressWarnings("unchecked")    @Test    public void testJSONArrayToObject(){        JSONArray jsonArray = JSONArray.fromObject(list);        List<User> newList = new ArrayList<>();        newList = JSONArray.toList(jsonArray,new User(),new JsonConfig());        System.out.println("測試JSONArray 轉  List");        for(User u:newList){            System.out.println(u.toString());        }    }        /*     * 測試 JSONObject 轉 Object     */    @Test    public void testJSONObjectToObject(){        JSONObject jsonObject = JSONObject.fromObject(new User("陳樂","21"));        User user = new User();        user = (User) JSONObject.toBean(jsonObject,new User(),new JsonConfig());        System.out.println("測試 JSONObject 轉 Object");        System.out.println(user);    }}

注意JSONArray.toList() 和 JSONObject.toBean() 方法裡面的參數!

 

運行結果:

測試JSONArray 轉  List
User [name=陳樂, age=21]
User [name=張卓鵬, age=20]


測試 JSONObject 轉 Object
User [name=陳樂, age=21]

 

JSON轉化為對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.