java-encapsulation generates JSON data and XML data classes

Source: Internet
Author: User

1. Background

Learn from the implementation of the App interface in PHP (PHP writes the app interface to generate XML and JSON data), encapsulating the Java version of the JSON and XML data manipulation classes!


2. Preparation

Before using, you need to introduce a JSON jar package: click I download!

Here implemented, object to JSON, object collection to JSON, object to XML, object collection to XML;


3.appUtil Tool class implementation

Concrete implementation of the process, I will not explain, while writing, while testing! Until the writing becomes stop!

The inside of the Tojsonarray () method is not used, can be deleted, but want to generate a JSON array, there is no need to delete!

Package Interface.app.util;import Java.util.hashmap;import Java.util.iterator;import java.util.map;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;public class Apputil {//default private static final String json= "JSON" ;  private static final String xml= "XML";  /** * Tool Class Entry * @param code status code * @param msg hint information * @param obj return data * @param type data type Json/xml * @return string  */public static string toprint (int code,string msg,object obj,string type) {//case does not affect String str= "";  if (json.equalsignorecase (type) &&json.equals (type)) {//generates JSON data str=tojsonstring (code, MSG, obj);  }else if (xml.equalsignorecase (type) &&xml.equals (type)) {//Generate XML Data Str=toxml (code, MSG, obj); }else{//JSON is used by default, the default is JSON str=tojsonstring (code, MSG, obj);} return str; }/** * object to JSON array * @param code status Code * @param msg status information * @param obj data * @return JSON array String */@SuppressWarnings ("unused") private static string Tojsonarray (int code,string msg,Object obj) {map<string, object> map=tokeyval (Code, MSG, obj); Jsonarray jsonarray=jsonarray.fromobject (map); return jsonarray.tostring ();  }/** * This one is enough!  * * Go to JSON Object * @param code status code * @param msg hint * @param obj data * @return JSON object String */private static string  tojsonstring (int code,string msg,object obj) {if (obj==null) {obj= "";}  Map<string, object> map=tokeyval (Code, MSG, obj); Jsonobject jsonobject=jsonobject.fromobject (map); return jsonobject.tostring ();  }/** * to XML Format: String assembly format * @param code Status code * @param msg hint information * @param obj data * @return XML data */private static     String toXml (int code,string msg,object obj) {if (obj==null) {obj= "";}    Map<string,object> map=tokeyval (Code, MSG, obj);  Jsonobject object=jsonobject.fromobject (map); StringBuilder builder=new StringBuilder ("<?xml version= ' 1.0 ' encoding= ' UTF-8 '?> '); Builder.append ("<root>"); Builder.append (Maptoxml (object)); Builder.append ("</root>"); Return BuilDer.tostring (); }/** * used to encapsulate data * @param code Status Code * @param msg information * @param obj data * @return */private static map<string, Object > tokeyval (int code,string msg,object obj) {map<string,object> map=new hashmap<string, Object> (); Map.put ("code", code); Map.put ("msg", msg); Map.put ("Data", "obj"); return map; }/** * Generate XML * @param object * @return */private static String maptoxml (Jsonobject object) {StringBuilder builder=new stri    Ngbuilder (); @SuppressWarnings ("Unchecked") iterator<string> Iterator=object.keys ();    while (Iterator.hasnext ()) {String key=iterator.next ();        Builder.append ("<" +key+ ">"); if (Object.get (key) instanceof Jsonobject) {//If Jsonobject is the case//Recursive call Builder.append (Maptoxml ((Jsonobject) object    . Get (key));    }else if (Object.get (key) instanceof Jsonarray) {//if jsonarray, StringBuilder builder2=new StringBuilder ();        Jsonarray array= (Jsonarray) object.get (key);       if (Array.isarray ()) {int i=0; for (OBject obj:array) {jsonobject objitem= (jsonobject) obj;              String attr= "num=" "+i+" ";              If there is an ID, you can use this//if (Objitem.containskey ("id")) {//attr= "Id= '" +objitem.getstring ("id") + "'";/}   Builder2.append ("<item" +attr+ ">");   Builder2.append (Maptoxml (objitem));   Builder2.append ("</item>");    i++;            }} builder.append (Builder2.tostring ());    }else{builder.append (Object.get (key));    } builder.append ("</" +key+ ">"); }return builder.tostring ();} }


4. Use

Use the URL to pass the type parameter, or when you call, write the value of type fixed!

1) Type=json: Generate JSON data,

2) Type=xml: Generate XML data,

3) No parameter or type to pass other values, are default values

Sample format:

http://localhost:8080/TennisGameSys/App_GetgameById?type=json&id=2

4) In this implementation of the call in the servlet, through the Doget () method to implement

  public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {          Set  the Encoding request.setcharacterencoding ("UTF-8");          Response.setcharacterencoding ("UTF-8");          Gets the URL parameter          String id=request.getparameter ("id");          String type=request.getparameter ("type");                  Query database                  gamemanager gm=new gamemanagerimpl ();  Game G=gm.getgamebyid (Integer.parseint (ID));  Encapsulates data  String strs= apputil.toprint (1, "Success", g, type);  Response.setcontenttype ("text/" +type);  Output Data  printwriter out=response.getwriter ();  Out.print (STRs);  Out.flush ();  Out.close ();}


Test results:

{"Data": {"Competitornum": "Enrolldeadline": "2015.8.1", "gamelocation": "Zhengzhou Sports Center", "Gamename": "Pepsi Innovation Tennis Competition", " Gametime ":" 2015.8.26 "," id ": 2," Personnum ": 2}," code ": 1," MSG ":" Success "}



5. Tools Download

http://download.csdn.net/detail/lablenet/9002325



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

java-encapsulation generates JSON data and XML data classes

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.