Lucene-based Case development: Jsonutil & Xmlutil

Source: Internet
Author: User
Tags readfile xpath

Reprint Please specify source: http://blog.csdn.net/xiaojimanman/article/details/43194015


From this blog to start the second most of the formal start, but before the introduction of the search background, but also to write about the possible use of the big tools class, so in the back of the search background, will not be interspersed with other content introduction. This article mainly introduces two tool classes: JSON, XML Format data processing class.

JSON
The JSON data format is a more commonly used method in the process of the pre-background communication. Convert JavaBean to JSON format strings, either through simple string concatenation or with third-party jar packages, the classes described here are also based on third-party jar packages. The code is implemented as follows:
 /** * @Description: JSON data tool */package com.lulei.util; Import Java.io.ioexception;import Java.util.hashmap;import com.fasterxml.jackson.annotation.JsonInclude.Include; Import Com.fasterxml.jackson.core.jsonprocessingexception;import Com.fasterxml.jackson.databind.jsonnode;import  Com.fasterxml.jackson.databind.ObjectMapper; public class Jsonutil {public static final string no_data = "{\" data\ ": null}";p ublic static final String No_result = "{\" R Esult\ ": false}";p rivate static Objectmapper mapper;static{mapper = new Objectmapper ();//When converting JSON, if the property value in the object is null, The attribute mapper.setserializationinclusion (include.non_null) is not generated;} /*** * @param JSON * @return when parsing fails return null * @Author: Lulei * @Description: JSON object given JSON string */public static Jsonnode Josn  2Object (String json) {try {return Mapper.readtree (JSON)} catch (Jsonprocessingexception e) {//TODO auto-generated catch Block E.printstacktrace (); return null;} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); return null;}}/*** * @param obj * @return When parsing fails return {datas:null} * @Author: Lulei * @Description: Generates JSON */public static strin for a given Java object G Parsejson (Object obj) {if (obj = = null) {return no_data;} try {return mapper.writevalueasstring (obj),} catch (Jsonprocessingexception e) {//TODO auto-generated catch block E.prin Tstacktrace (); return no_data;}} /*** * @param obj * @param root * @return When parsing fails return {datas:null} * @Author: Lulei * @Description: The corresponding JSON is generated for a given Java object, you can specify a JSO The root name of n */public static String Parsejson (Object obj, String root) {if (obj = = null) {return no_data;} try {StringBuilder sb = new StringBuilder (); Sb.append ("{\" "); Sb.append (root); Sb.append (" \ ":"); Sb.append ( Mapper.writevalueasstring (obj)); Sb.append ("}"); return sb.tostring ();} catch (Jsonprocessingexception e) {//TODO auto-generated catch Blocke.printstacktrace (); return no_data;}} /*** * @param json * @param var * @return If the incoming VAR is null, the default variable is named Datas * @Author: Lulei * @Description: Wraps a JSON string into JSONP, for example VA R data={} mode */public static String Wrapperjsonp(string json, string var) {if (var = = null) {var = "datas";} return new StringBuilder (). Append ("var"). Append (Var). Append ("="). Append (JSON). toString ();} public static void Main (string[] args) {hashmap<string, integer> hash = new hashmap<string, integer> (); hash.p UT ("Key1", 1); Hash.put ("Key2", 2); Hash.put ("Key3", 3); System.out.println (Jsonutil.parsejson (hash));}}


Of course, the third-party jar package is once again encapsulated in the project easier to use, the main function above the result is as follows (data is processed in a format):


As for other methods if interested can test themselves.

XML
In the process of communicating with the foreground, the XML data format is also a common method, while the XML data format is also a form of a background configuration file. The processing of XML data, there are many third-party jar package, this is the use of dom4j, the code is implemented as follows:
 /** * @Description: XML Tool class */package com.lulei.util; Import Java.io.bufferedreader;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.stringwriter;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbexception;import Javax.xml.bind.marshaller;import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.documenthelper;import Org.dom4j.node;public class Xmlutil {private static String Noresult = "<root>no Result</root> ";/** * @param obj * @return * @Author: Lulei * @Description: Convert Java objects to XML-formatted strings */public static Stri ng parseobjtoxmlstring (Object obj) {if (obj = = null) {return noresult;} StringWriter SW = new StringWriter (); Jaxbcontext Jaxbcontext; Marshaller marshaller;try {jaxbcontext = Jaxbcontext.newinstance (Obj.getclass ()); Marshaller = Jaxbcontext.createmarshaller (); Marshaller.marshal (obj, SW); return sw.tostring ();} catch (JaxbexcePtion e) {//TODO auto-generated catch block E.printstacktrace ();} return noresult;} /** * @param XML * @return * @Author: Lulei * @Description: Convert an XML string object to an XML object */public static Document Createfromstr ING (String xml) {try {return documenthelper.parsetext (XML);} catch (Documentexception e) {e.printstacktrace (); return null;}} /** * @param XPath * @param node * @return * @Author: Lulei * @Description: Gets the text of the specified XPath when parsing fails returns null */public static STR ing Gettextfromnode (String xpath,node Node) {try {return Node.selectsinglenode (XPath). GetText ();} catch (Exception e) { return null;}} /** * @param path * @Author: Lulei * @Description: Read XML file * document */public static document CREATEFRO @return XML file MPath (String path) {return createfromstring (readFile (path));}  /** * @param path * @Author: Lulei * @Description: Read file * @return return file content string */private static string ReadFile (string path) {File File = new file (path); FileInputStream FileInputStream; StringBuffer sb = new StringBuffer (); try {fileinputsTream = new FileInputStream (file);//error using UTF-8 to read the contents of string charset = Charsetutil.getstreamcharset (File.touri (). Tourl (), "Utf-8"); InputStreamReader InputStreamReader = new InputStreamReader (FileInputStream, CharSet); BufferedReader BufferedReader = new BufferedReader (InputStreamReader); String S;while ((s = bufferedreader.readline ()) = null) {s = s.replaceall ("\ T", ""). Trim (); if (s.length () > 0) {sb.appen D (s);}} Fileinputstream.close (); Bufferedreader.close (); Fileinputstream.close ();} catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (IOException e) {//TODO Auto-generated Catch block E.printstacktrace ();} return sb.tostring ();} public static void Main (string[] args) {}}


A use case for Xmlutil is as follows:
/**   * @Description: Chapter List search Results     */package com.lulei.test;  Import Java.util.arraylist;import Javax.xml.bind.annotation.xmlrootelement;import com.lulei.util.XmlUtil; @XmlRootElement (name = "root") public class Testxmlutil {private int count;private arraylist<string> result;public Testxmlutil () {count = 3;result = new arraylist<string> (); Result.add ("test1"); Result.add ("test2"); Result.add (" Test3 ");} public int GetCount () {return count;} public void SetCount (int count) {This.count = count;} Public arraylist<string> GetResult () {return result;} public void Setresult (arraylist<string> result) {This.result = result;} public static void Main (string[] args) {System.out.println (xmlutil.parseobjtoxmlstring (New Testxmlutil ()));}}


The results of the operation are as shown (data is formatted and processed):


In the Xmlutil class to use the Charsetutil class, about the Charsetutil class in the future blog in detail (the main role is to detect the file or stream encoding method, etc.).

PS: Recently found other sites may be reproduced on the blog, there is no source link, if you want to see more about Lucene-based case development please click here. Or visit the URL http://blog.csdn.net/xiaojimanman/article/category/2841877

Lucene-based Case development: Jsonutil & Xmlutil

Related Article

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.