Reference documents: http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html
First, Jsonobject
1.JAR Package Introduction
To enable the program to run, the Json-lib package must be introduced, and the Json-lib package relies on the following jar packages:
- Commons-lang.jar
- Commons-beanutils.jar
- Commons-collections.jar
- Commons-logging.jar
- Ezmorph.jar
- Json-lib-2.4-jdk15.jar
- Json-lib-2.4-jdk15-javadoc.jar
- Json-lib-2.4-jdk15-sources.jar
2.JSONObject Object Use
The Json-lib package is a Beans,collections,maps,java arrays and XML and JSON transforms each other's packages. In this example, we will use the Jsonobject class to create the Jsonobject object, and then we print the values of those objects. In order to use the Jsonobject object, we will introduce the "Net.sf.json" package. To add elements to an object, we use the put () method.
[Java]View Plaincopy
- Public static User Getuserfromjson (String json) {
- User user = new user ();
- try {
- Jsonobject obj = Jsonobject.fromobject (JSON);
- User.setuserid (Obj.getint (Tables.User.Fields.USERID));
- User.setaccount (obj.getstring (Tables.User.Fields.ACCOUNT));
- User.setpassword (obj.getstring (Tables.User.Fields.PASSWORD));
- User.setgender (Obj.getint (Tables.User.Fields.GENDER));
- User.setpermission (Obj.getint (Tables.User.Fields.PERMISSION));
- User.setname (obj.getstring (Tables.User.Fields.NAME));
- User.setremark (obj.getstring (Tables.User.Fields.REMARK));
- User.setcontact (obj.getstring (Tables.User.Fields.CONTACT));
- return user;
- } catch (Exception ex) {
- Ex.printstacktrace ();
- }
- return null;
- }
Second, Gson processing JSON format data
1.Object to JSON format
[Java]View Plaincopy
- Public String Getallvideosbyjson () throws Exception {
- list<video> videos = Service.getallvideos ();
- StringBuilder sb = new StringBuilder ();
- //gson Gson = new Gson ();
- Gson Gson = new Gson ();
- String result = Gson.tojson (videos);
- return result;
- }
string in 2.json format becomes video object
[Java]View Plaincopy
- Public static list<video> getjsonallvideos_2 () throws Exception {
- String path = "Http://192.168.2.107:8080/VideoWeb/VideoServlet?format=json&type=get";
- URL url = new URL (path);
- HttpURLConnection conn = (httpurlconnection) url.openconnection ();
- Conn.setreadtimeout (5 * 1000);
- Conn.setrequestmethod ("GET");
- InputStream instream = Conn.getinputstream ();
- byte[] data = Streamtool.readinputstream (instream);
- String json = new string (data);
- Type typelist = new typetoken<arraylist<video>> () {
- }.gettype ();
- Gson Gson = new Gson ();
- arraylist<video> videos = Gson.fromjson (JSON, typelist);
- return videos;
- }
Jsonobject and Gson detailed