Json_ 0 Base _008_ Converts a JSON-formatted "array" string to a list collection

Source: Internet
Author: User
Tags string format

Converts a JSON-formatted "array" string to a list collection.

Apply this technique to get a Java-corresponding object from a JSON object string format.
Jsonobject is a "name.values" collection,
The value portion (string) corresponding to key is obtained by the Get (key) method.
A Jsonobject object can be obtained by Getjsonobject (key).
A Jsonarray object can be obtained by Getjsonarray (key).

To import a jar package:

Write: Po (Bean) Class:

Package Com.west.webcourse.po;/** No. 01 Step: Write The Bean class, * next Com.west.webcourse.servlet.JavaBeanToJOSNString.java*/ Public classPersoninfopo {PrivateString name; Private intAge ; PrivateString sex;  PublicPersoninfopo () {} Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }    }

No. 02 Step: Writing The servlet class:

Package Com.west.webcourse.servlet;import Java.io.ioexception;import java.io.printwriter;import Java.util.arraylist;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.west.webcourse.po.personinfopo;import Net.sf.json.JSONArray; Import Net.sf.json.JSONObject; Public classJavabeantojosnstring extends HttpServlet {personinfopo pif=NewPersoninfopo (); Personinfopo pif01=NewPersoninfopo (); /** No. 03 step: Rewrite the Doget () method, Next: Test*/@Overrideprotected voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Response.getwriter (); System. out. println ("Conversion");  out. Print ("the converted JSON string:<br/>"); /** Send a JSON-formatted string to the browser*/getjsonstringtobeanlist ();  out. Flush ();  out. Close (); }    /** No. 02 Step: Convert the JSON type string to: List Collection Object*/     PublicList<personinfopo>getjsonstringtobeanlist () {String jsonstring="[{\ "name\": \ "zhang3\", \ "sex\": \ "nan\", \ "age\": \ "30\"},{\ "name\": \ "zhang4\", \ "sex\": \ "nan4\", \ "age\": \ "304\ "}]"; System. out. println (jsonstring); /*2.1: Convert to JSON array*/        Try {            /*2.2: Create the list of Personinfopo objects*/List<PersonInfoPo> LP =NewArraylist<personinfopo>(); /**2.3:json string, converted to Jsonarray array*/Jsonarray Pojsonarray=Jsonarray.fromobject (jsonstring); /** 2.4: Iterate through the array, remove the Jsonobject object and convert it to a Personinfopo object, add to the list*/             for(ObjectObject: Pojsonarray) {Personinfopo pif02=NewPersoninfopo (); /**2.4.1: Converting Jsonobject objects to Personinfopo objects*/pif02= (Personinfopo) Jsonobject.tobean ((Jsonobject)Object, Personinfopo.class);                Lp.add (PIF02); System. out. println ("Loading :"+pif02.getname ()); }            returnLP; } Catch(Exception e) {e.printstacktrace (); }        return NULL; }}

To test the servlet:

Package Com.west.webcourse.servlet;/** * Test*/Import Java.util.list;import Org.junit.beforeclass;import org.junit.test;import Com.west.webcourse.po.PersonInfoPo; Public classJavabeantojosnstringtest {Staticjavabeantojosnstring JS; @BeforeClass Public Static voidSetupbeforeclass () throws Exception {JS=Newjavabeantojosnstring (); } @Test Public voidtestgetjsonstringtobeanlist () {List<PersonInfoPo> lp=js.getjsonstringtobeanlist ();  for(Personinfopo person:lp) {System. out. println ("test, loop out:"+person.getname ()); }    }}

Json_ 0 Base _008_ Converts a JSon-formatted "array" string to a list collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.