JSON(JavaScript Object notation) is a lightweight data interchange format.
Easy for people to read and write. It is also easy to machine parse and generate
Json-lib Official website: http://json-lib.sourceforge.net/
Jackson's official website: http://jackson.codehaus.org/
The fastest-performing JSON processor Jackson is much higher than json_lib
Convert JSON string:
/** * using Jackson to generate JSON format strings * * @author archie2010 since 2011-4-26 pm 05:59:46/public class Jacksontest {private static Jsongenerator jsongenerator = null; private static Objectmapper objectmapper = null; private static user user = null; /** * Convert entity to JSON String * @throws IOException */public static void Writeentity2json () throws ioexception{System.out.println (" Using Jsongenerator transform entity to JSON string-------------"); WriteObject can convert Java objects, Eg:javabean/map/list/array, and other jsongenerator.writeobject (user); System.out.println (); System.out.println ("Use Objectmapper-----------"); WriteValue has the same function as WriteObject objectmapper.writevalue (System.out, user); /** * Convert Map to JSON string * @throws jsongenerationexception * @throws jsonmappingexception * @throws ioexception * * Public STA tic void Writemap2json () throws Jsongenerationexception, Jsonmappingexception, ioexception{System.out.println (" Convert map to String--------"); Map<string, object> map=new hashmap<string, object> (); Map.put ("Uname", User.getuname ()); Map.put ("Upwd", User.getupwd ()); Map.put ("user", user); Objectmapper.writevalue (System.out, map); /** * Convert list to JSON string * @throws IOException * @throws jsonmappingexception * @throws jsongenerationexception/Public St atic void Writelist2json () throws ioexception{list<user> userlist=new arraylist<user> (); UserList.add ( user); User U=new user (); U.setuid (10); U.setuname ("Archie"); U.setupwd ("123"); Userlist.add (U); Objectmapper.writevalue (System.out, userlist); Objectmapper.writevalue (System.out, userlist); public static void Main (string[] args) {user = new user (); User.setuid (5); User.setuname ("Tom"); User.setupwd ("123"); u Ser.setnumber (3.44); Objectmapper = new Objectmapper (); try {jsongenerator = Objectmapper.getjsonfactory (). Createjsongenerator (System.out, Jsonencoding.utf8); Writeentity2json (); Writemap2json (); Writelist2json (); catch (IOException e) {e.printstacktrace ();}} }
[{"Number": 3.44, "uname": "Tom", "Upwd": "123", "UID": 5},{"number": 0.0, "uname": "Archie", "Upwd": "123", "UID": 10}]
Output to browser end:
StringWriter writer = new StringWriter (); Objectmapper mapper = new Objectmapper (); try {mapper.writevalue (writer, hmap);} catch (Jsongenerationexception e) {e.printstacktrace ();} catch (Jsonmappingexce Ption e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} response.setcontenttype ("Text/html;chars Et=utf-8 "); PrintWriter out= Response.getwriter (); Out.print (Writer.tostring ());