分享

基于lucene的案例开发10:搜索后台基础,JsonUtil & XmlUtil类介绍

本帖最后由 nettman 于 2015-4-16 22:40 编辑

问题导读

1.什么是json?
2.给定java对象如何实现生成对应json?
3.如何实现将java对象转化为xml格式的字符串?







接上篇
基于lucene的案例开发9:案例初识



   从这篇博客开始第二大部分就算正式开始了,不过在介绍搜索后台之前,还是先介绍写可能使用的大工具类,这样在后面的搜索后台介绍中,就不会穿插其他的内容介绍。这篇就主要介绍两个工具类:json、xml格式数据处理类。

JSON
      在前后台数据通信过程中,json数据格式是一种比较常用的方式。将javabean转化为json格式字符串,可以通过简单的字符串拼接,也可以使用第三方jar包进行处理,这里介绍的类也是基于第三方jar包实现的。代码实现如下:

  1. /**   
  2. *@Description:    json数据工具
  3. */   
  4. package com.lulei.util;   
  5.   
  6. import java.io.IOException;  
  7. import java.util.HashMap;  
  8.   
  9. import com.fasterxml.jackson.annotation.JsonInclude.Include;  
  10. import com.fasterxml.jackson.core.JsonProcessingException;  
  11. import com.fasterxml.jackson.databind.JsonNode;  
  12. import com.fasterxml.jackson.databind.ObjectMapper;  
  13.    
  14. public class JsonUtil {  
  15.       
  16.     public static final String NO_DATA = "{"data":null}";  
  17.     public static final String NO_RESULT = "{"result":false}";  
  18.     private static ObjectMapper mapper;  
  19.     static{  
  20.         mapper = new ObjectMapper();  
  21.         //转换json时,如果对象中属性值为null,则不生成该属性  
  22.         mapper.setSerializationInclusion(Include.NON_NULL);  
  23.     }  
  24.       
  25.     /***
  26.      * @param json
  27.      * @return 当解析失败返回null
  28.      * @Author: lulei  
  29.      * @Description: 给定json字符串获得json对象
  30.      */  
  31.     public static JsonNode josn2Object(String json){  
  32.          try {  
  33.             return mapper.readTree(json);  
  34.         } catch (JsonProcessingException e) {  
  35.             // TODO Auto-generated catch block   
  36.             e.printStackTrace();  
  37.             return null;  
  38.         } catch (IOException e) {  
  39.             // TODO Auto-generated catch block   
  40.             e.printStackTrace();  
  41.             return null;  
  42.         }  
  43.     }  
  44.       
  45.     /***
  46.      * @param obj
  47.      * @return 当解析失败返回{datas:null}
  48.      * @Author: lulei   
  49.      * @Description: 给定java对象生成对应json
  50.      */  
  51.     public static String parseJson(Object obj){  
  52.          
  53.         if(obj == null){  
  54.             return NO_DATA;  
  55.         }  
  56.          
  57.         try {  
  58.             return mapper.writeValueAsString(obj);  
  59.         } catch (JsonProcessingException e) {  
  60.             // TODO Auto-generated catch block   
  61.             e.printStackTrace();  
  62.             return NO_DATA;  
  63.         }  
  64.     }  
  65.       
  66.     /***
  67.      * @param obj
  68.      * @param root
  69.      * @return 当解析失败返回{datas:null}
  70.      * @Author: lulei   
  71.      * @Description:给定java对象生成对应json,可以指定一个json的root名
  72.      */  
  73.     public static String parseJson(Object obj, String root){  
  74.          
  75.         if(obj == null){  
  76.             return NO_DATA;  
  77.         }  
  78.          
  79.         try {  
  80.             StringBuilder sb = new StringBuilder();  
  81.             sb.append("{"");  
  82.             sb.append(root);  
  83.             sb.append("":");  
  84.             sb.append(mapper.writeValueAsString(obj));  
  85.             sb.append("}");  
  86.             return sb.toString();  
  87.         } catch (JsonProcessingException e) {  
  88.             // TODO Auto-generated catch block  
  89.             e.printStackTrace();  
  90.             return NO_DATA;  
  91.         }  
  92.     }  
  93.       
  94.     /***
  95.      * @param json
  96.      * @param var
  97.      * @return 若传入var为null,则默认变量名为datas
  98.      * @Author: lulei   
  99.      * @Description:将json字符串包装成jsonp,例如var data={}方式
  100.      */  
  101.     public static String wrapperJsonp(String json, String var){  
  102.         if(var == null){  
  103.             var = "datas";  
  104.         }  
  105.         return new StringBuilder().append("var ").append(var).append("=").append(json).toString();  
  106.     }  
  107.       
  108.     public static void main(String[] args) {  
  109.         HashMap<String, Integer> hash = new HashMap<String, Integer>();  
  110.         hash.put("key1", 1);  
  111.         hash.put("key2", 2);  
  112.         hash.put("key3", 3);  
  113.         System.out.println(JsonUtil.parseJson(hash));  
  114.     }  
  115. }  
复制代码


1.png

      当然这里对第三方jar包进行再一次封装在项目中更简单的使用,上述main函数的运行结果如下(数据经过格式话处理):



      至于其他方法如若感兴趣可以自行测试。

XML
      在和前台的通信的过程中,xml数据格式也是一种常用方法,同时xml数据格式也是后台配置文件的一种形式。对xml数据的处理,有很多第三方jar包,这是使用的是dom4j,代码实现如下:


  1. /**   
  2. *@Description: Xml工具类     
  3. */   
  4. package com.lulei.util;   
  5.   
  6. import java.io.BufferedReader;  
  7. import java.io.File;  
  8. import java.io.FileInputStream;  
  9. import java.io.FileNotFoundException;  
  10. import java.io.IOException;  
  11. import java.io.InputStreamReader;  
  12. import java.io.StringWriter;  
  13.   
  14. import javax.xml.bind.JAXBContext;  
  15. import javax.xml.bind.JAXBException;  
  16. import javax.xml.bind.Marshaller;  
  17.   
  18. import org.dom4j.Document;  
  19. import org.dom4j.DocumentException;  
  20. import org.dom4j.DocumentHelper;  
  21. import org.dom4j.Node;  
  22.   
  23. public class XmlUtil {  
  24.     private static String noResult = "<root>no result</root>";  
  25.   
  26.     /**
  27.      * @param obj
  28.      * @return
  29.      * @Author:lulei   
  30.      * @Description: 将java对象转化为xml格式的字符串
  31.      */  
  32.     public static String parseObjToXmlString(Object obj){  
  33.         if (obj == null) {  
  34.             return noResult;  
  35.         }  
  36.         StringWriter sw = new StringWriter();  
  37.         JAXBContext jAXBContext;  
  38.         Marshaller marshaller;  
  39.         try {  
  40.             jAXBContext = JAXBContext.newInstance(obj.getClass());  
  41.             marshaller = jAXBContext.createMarshaller();  
  42.             marshaller.marshal(obj, sw);  
  43.             return sw.toString();  
  44.         } catch (JAXBException e) {  
  45.             // TODO Auto-generated catch block   
  46.             e.printStackTrace();  
  47.         }  
  48.         return noResult;  
  49.     }  
  50.       
  51.     /**
  52.      * @param xml
  53.      * @return
  54.      * @Author: lulei   
  55.      * @Description: 将xml String对象转化为xml对象
  56.      */  
  57.     public static Document createFromString(String xml){  
  58.         try {  
  59.             return DocumentHelper.parseText(xml);  
  60.         } catch (DocumentException e) {  
  61.             e.printStackTrace();  
  62.             return null;  
  63.         }  
  64.     }  
  65.       
  66.     /**
  67.      * @param xpath
  68.      * @param node
  69.      * @return
  70.      * @Author: lulei   
  71.      * @Description: 获取指定xpath的文本,当解析失败返回null
  72.      */  
  73.     public static String getTextFromNode(String xpath,Node node){  
  74.         try {  
  75.             return node.selectSingleNode(xpath).getText();  
  76.         } catch (Exception e) {  
  77.             return null;  
  78.         }  
  79.     }  
  80.       
  81.     /**
  82.      * @param path
  83.      * @Author: lulei   
  84.      * @Description: 读取xml文件
  85.      * @return xml文件对应的Document
  86.      */  
  87.     public static Document createFromPath(String path){  
  88.         return createFromString(readFile(path));  
  89.     }  
  90.       
  91.     /**
  92.      * @param path
  93.      * @Author: lulei   
  94.      * @Description: 读文件
  95.      * @return 返回文件内容字符串
  96.      */  
  97.     private static String readFile(String path) {  
  98.         File file = new File(path);  
  99.         FileInputStream fileInputStream;  
  100.         StringBuffer sb = new StringBuffer();  
  101.         try {  
  102.             fileInputStream = new FileInputStream(file);  
  103.             //错误使用UTF-8读取内容  
  104.             String charset = CharsetUtil.getStreamCharset(file.toURI().toURL(), "utf-8");  
  105.             InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charset);  
  106.             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  107.             String s;  
  108.             while ((s = bufferedReader.readLine()) != null){  
  109.                 s = s.replaceAll("\t", "").trim();  
  110.                 if (s.length() > 0){  
  111.                     sb.append(s);  
  112.                 }  
  113.             }  
  114.             fileInputStream.close();  
  115.             bufferedReader.close();  
  116.             fileInputStream.close();  
  117.         } catch (FileNotFoundException e) {  
  118.             // TODO Auto-generated catch block   
  119.             e.printStackTrace();  
  120.         } catch (IOException e) {  
  121.             // TODO Auto-generated catch block   
  122.             e.printStackTrace();  
  123.         }   
  124.         return sb.toString();  
  125.     }  
  126.       
  127.     public static void main(String[] args) {  
  128.     }  
  129. }  
复制代码



      XmlUtil的一个使用事例如下所示:


  1. /**   
  2. *@Description: 章节列表搜索结果     
  3. */   
  4. package com.lulei.test;   
  5.   
  6. import java.util.ArrayList;  
  7.   
  8. import javax.xml.bind.annotation.XmlRootElement;  
  9.   
  10. import com.lulei.util.XmlUtil;  
  11.    
  12. @XmlRootElement(name = "root")  
  13. public class TestXmlUtil {  
  14.     private int count;  
  15.     private ArrayList<String> result;  
  16.       
  17.     public TestXmlUtil() {  
  18.         count = 3;  
  19.         result = new ArrayList<String>();  
  20.         result.add("test1");  
  21.         result.add("test2");  
  22.         result.add("test3");  
  23.     }  
  24.       
  25.     public int getCount() {  
  26.         return count;  
  27.     }  
  28.     public void setCount(int count) {  
  29.         this.count = count;  
  30.     }  
  31.     public ArrayList<String> getResult() {  
  32.         return result;  
  33.     }  
  34.     public void setResult(ArrayList<String> result) {  
  35.         this.result = result;  
  36.     }  
  37.       
  38.     public static void main(String[] args) {  
  39.         System.out.println(XmlUtil.parseObjToXmlString(new TestXmlUtil()));  
  40.     }  
  41. }  
复制代码



运行结果如下图所示(数据经过格式话处理):

2.png

在XmlUtil类中使用到了CharsetUtil类,关于CharsetUtil类在以后的博客中再详细介绍(主要作用就是检测文件或者流的编码方式等)。



相关内容:
基于lucene的案例开发1:lucene初始认知

基于lucene的案例开发2:索引数学模型

基于lucene的案例开发3:索引文件结构

基于lucene的案例开发4:创建索引

基于lucene的案例开发5:搜索索引

基于lucene的案例开发6:分词器介绍

基于lucene的案例开发7:Query查询

基于lucene的案例开发8:IndexSearcher中检索方法

基于lucene的案例开发9:案例初识

基于lucene的案例开发10:搜索后台基础,JsonUtil & XmlUtil类介绍

基于lucene的案例开发11:项目常用类ClassUtil & CharsetUtil介绍

基于lucene的案例开发12:数据库连接池

基于lucene的案例开发13:实现实时索引基本原理

基于lucene的案例开发14:实时索引管理类IndexManager

基于lucene的案例开发15:实时索引的检索

基于lucene的案例开发16:实时索引的修改

基于lucene的案例开发17:查询语句创建PackQuery

基于lucene的案例开发18:纵横小说更新列表页抓取

基于lucene的案例开发19:纵横小说简介页采集

基于lucene的案例开发20:纵横小说章节列表采集

基于lucene的案例开发21:纵横小说阅读页采集


加微信w3aboutyun,可拉入技术爱好者群

已有(2)人评论

跳转到指定楼层
漂泊一剑客 发表于 2015-6-14 23:57:39
一口气看了10篇,感谢楼主这样的好心人,热心人
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条