Json_ 0 Base _005_ to convert the PO (Bean) Object Collection list to a JSON-formatted object string, returned to the interface

Source: Internet
Author: User

Converts a list of PO (Bean) objects to a JSON-formatted object string, which is returned to the interface

To import a jar package:

Write: Po (bean) Code:

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; }    }

To write the servlet code:

Package Com.west.webcourse.servlet;import Java.io.ioexception;import java.io.printwriter;import Java.util.arraylist;import java.util.hashmap;import java.util.hashset;import Java.util.list;import java.util.Map; Import Java.util.set;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; 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*/         out. Print (getbeanstojsonstring ());  out. Flush ();  out. Close (); }    /** No. 02 Step: Create a JSON format string conversion method: Convert a collection of PO objects to a JSON type string*/     PublicString getbeanstojsonstring () {Pif.setage (1); Pif.setname ("name"); Pif.setsex ("Sex"); Pif01.setage (101); Pif01.setname ("name01"); Pif01.setsex ("sex01"); List LP=NewArrayList ();        Lp.add (PIF);        Lp.add (PIF01); Jsonarray Beantojsonarray=NewJsonarray (). FROMOBJECT (LP); System. out. println (Beantojsonarray); returnbeantojsonarray.tostring (); }}

To test the servlet code:

Package Com.west.webcourse.servlet;/** No. 04 Step: Test * Next: Configure Web. XML*/import Org.junit.beforeclass;import org.junit.Test; Public classJavabeantojosnstringtest {Staticjavabeantojosnstring JS; @BeforeClass Public Static voidSetupbeforeclass () throws Exception {JS=Newjavabeantojosnstring (); } @Test Public voidtesttojsonstring () {js.getbeanstojsonstring (); }}

Configure Web. XML:

<?xml version="1.0"encoding="UTF-8"? ><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://java.sun.com/xml/ns/javaee"xsi:schemalocation="Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"version="2.5"> <display-name></display-name> <servlet> <description>This</description> <dis Play-name>this</display-name> <servlet-name>JavaBeanToJOSNString</servlet-name> < servlet-class>com.west.webcourse.servlet.javabeantojosnstring</servlet-class> </servlet> <servlet-mapping> <servlet-name>JavaBeanToJOSNString</servlet-name> <ur L-pattern>/javabeantojosnstring</url-pattern> </servlet-mapping> <welcome-file-list> < Welcome-file>personinfo.jsp</welcome-file> </welcome-file-list></web-app>

Authoring Interface: personinfo.jsp

<%@ page language="Java"import="java.util.*"pageencoding="UTF-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () +"://"+ request.getservername () +":"+Request.getserverport ()+ Path +"/";%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en">Basehref="<%=basePath%>"><title>my JSP'personinfo.jsp'Starting Page</title><meta http-equiv="pragma"Content="No-cache"><meta http-equiv="Cache-control"Content="No-cache"><meta http-equiv="Expires"Content="0"><meta http-equiv="keywords"Content="Keyword1,keyword2,keyword3"><meta http-equiv="Description"Content="This is my page"><!--<link rel="stylesheet"Type="Text/css"href="Styles.css">-->dynamically get the directory for the current project's ContextPath: ${pagecontext.request.contextpath}<br> <a href="javabeantojosnstring"> Send request to servlet </a> <br></body>

Json_ 0 Base _005_ to convert the PO (Bean) Object Collection list to a JSON-formatted object string, returned to the interface

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.