標籤:lucene java json xml
轉載請註明出處:http://blog.csdn.net/xiaojimanman/article/details/43194015
從這篇部落格開始第二大部分就算正式開始了,不過在介紹搜尋後台之前,還是先介紹寫可能使用的大工具類,這樣在後面的搜尋後台介紹中,就不會穿插其他的內容介紹。這篇就主要介紹兩個工具類:json、xml格式資料處理類。
JSON
在前後台資料通訊過程中,json資料格式是一種比較常用的方式。將javabean轉化為json格式字串,可以通過簡單的字串拼接,也可以使用第三方jar包進行處理,這裡介紹的類也是基於第三方jar包實現的。代碼實現如下:
/** *@Description: json資料工具 */ 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}";public static final String NO_RESULT = "{\"result\":false}";private static ObjectMapper mapper;static{mapper = new ObjectMapper();//轉換json時,如果對象中屬性值為null,則不產生該屬性mapper.setSerializationInclusion(Include.NON_NULL);}/*** * @param json * @return 當解析失敗返回null * @Author: lulei * @Description: 給定json字串獲得json對象 */public static JsonNode josn2Object(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 當解析失敗返回{datas:null} * @Author: lulei * @Description: 給定java對象產生對應json */public static String parseJson(Object obj){if(obj == null){return NO_DATA;}try {return mapper.writeValueAsString(obj);} catch (JsonProcessingException e) {// TODO Auto-generated catch block e.printStackTrace();return NO_DATA;}}/*** * @param obj * @param root * @return 當解析失敗返回{datas:null} * @Author: lulei * @Description:給定java對象產生對應json,可以指定一個json的root名 */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 若傳入var為null,則預設變數名為datas * @Author: lulei * @Description:將json字串封裝成jsonp,例如var data={}方式 */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.put("key1", 1);hash.put("key2", 2);hash.put("key3", 3);System.out.println(JsonUtil.parseJson(hash));}}
當然這裡對第三方jar包進行再一次封裝在項目中更簡單的使用,上述main函數的運行結果如下(資料經過格式話處理):
至於其他方法如若感興趣可以自行測試。
XML
在和前台的通訊的過程中,xml資料格式也是一種常用方法,同時xml資料格式也是後台設定檔的一種形式。對xml資料的處理,有很多第三方jar包,這是使用的是dom4j,代碼實現如下:
/** *@Description: Xml工具類 */ 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: 將java對象轉化為xml格式的字串 */public static String 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: 將xml String對象轉化為xml對象 */public static Document createFromString(String xml){try {return DocumentHelper.parseText(xml);} catch (DocumentException e) {e.printStackTrace();return null;}}/** * @param xpath * @param node * @return * @Author: lulei * @Description: 擷取指定xpath的文本,當解析失敗返回null */public static String getTextFromNode(String xpath,Node node){try {return node.selectSingleNode(xpath).getText();} catch (Exception e) {return null;}}/** * @param path * @Author: lulei * @Description: 讀取xml檔案 * @return xml檔案對應的Document */public static Document createFromPath(String path){return createFromString(readFile(path));}/** * @param path * @Author: lulei * @Description: 讀檔案 * @return 返迴文件內容字串 */private static String readFile(String path) {File file = new File(path);FileInputStream fileInputStream;StringBuffer sb = new StringBuffer();try {fileInputStream = new FileInputStream(file);//錯誤使用UTF-8讀取內容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.append(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) {}}
XmlUtil的一個使用案例如下所示:
/** *@Description: 章節列表搜尋結果 */ 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()));}}
運行結果如所示(資料經過格式話處理):
在XmlUtil類中使用到了CharsetUtil類,關於CharsetUtil類在以後的部落格中再詳細介紹(主要作用就是檢測檔案或者流的編碼方式等)。
ps:最近發現其他網站可能會對部落格轉載,上面並沒有源連結,如想查看更多關於 基於lucene的案例開發 請點擊這裡。或訪問網址http://blog.csdn.net/xiaojimanman/article/category/2841877
基於lucene的案例開發:JsonUtil & XmlUtil