標籤: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轉化為對象