I've previously written an object into json,http://www.cnblogs.com/loger1995/p/6613488.html.
Now write a way to convert JSON into objects, and where to look!
Guide Package:
These packages through Baidu keyword: jsonobject must be 6 bags to find!
Create a new test class:
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 classTestjson { Public Staticlist<user> list =NewArraylist<>(); Static{List.add (NewUser ("Tran Le"," +")); List.add (NewUser ("Zhang Zho-peng"," -")); } /** Test Jsonarray go to List*/@SuppressWarnings ("unchecked") @Test Public voidTestjsonarraytoobject () {Jsonarray Jsonarray=jsonarray.fromobject (list); List<User> NewList =NewArraylist<>(); NewList= Jsonarray.tolist (Jsonarray,NewUser (),Newjsonconfig ()); System. out. println ("Test Jsonarray Goto List"); for(User u:newlist) {System. out. println (U.tostring ()); } } /** Test Jsonobject to Object*/@Test Public voidTestjsonobjecttoobject () {jsonobject jsonobject= Jsonobject.fromobject (NewUser ("Tran Le"," +")); User User=NewUser (); User= (User) Jsonobject.tobean (Jsonobject,NewUser (),Newjsonconfig ()); System. out. println ("test Jsonobject to Object"); System. out. println (user); }}
Note the parameters inside the Jsonarray.tolist () and Jsonobject.tobean () methods!
Operation Result:
Test Jsonarray Goto List
User [Name= Tran Le, age=21]
User [name= Zhang Zho-peng, age=20]
Test Jsonobject to Object
User [Name= Tran Le, age=21]
JSON conversion to Object