转载请注明出处: http://www.voidcn.com/article/p-bxtmsdvr-bkz.html
从这篇博客开始第二大部分就算正式开始了,不过在介绍搜索后台之前,还是先介绍写可能使用的大工具类,这样在后面的搜索后台介绍中,就不会穿插其他的内容介绍。这篇就主要介绍两个工具类:json、xml格式数据处理类。
JSON
在前后台数据通信过程中,json数据格式是一种比较常用的方式。将javabean转化为json格式字符串,可以通过简单的字符串拼接,也可以使用第三方jar包进行处理,这里介绍的类也是基于第三方jar包实现的。代码实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 1 /**
2 *@Description: json数据工具
3 */
4package com.lulei.util;
5
6import java.io.IOException;
7import java.util.HashMap;
8
9import com.fasterxml.jackson.annotation.JsonInclude.Include;
10import com.fasterxml.jackson.core.JsonProcessingException;
11import com.fasterxml.jackson.databind.JsonNode;
12import com.fasterxml.jackson.databind.ObjectMapper;
13
14public 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}
116
117
1
2 1 当然这里对第三方jar包进行再一次封装在项目中更简单的使用,上述main函数的运行结果如下(数据经过格式话处理):
2
至于其他方法如若感兴趣可以自行测试。
XML
在和前台的通信的过程中,xml数据格式也是一种常用方法,同时xml数据格式也是后台配置文件的一种形式。对xml数据的处理,有很多第三方jar包,这是使用的是dom4j,代码实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131 1 /**
2 *@Description: Xml工具类
3 */
4package com.lulei.util;
5
6import java.io.BufferedReader;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileNotFoundException;
10import java.io.IOException;
11import java.io.InputStreamReader;
12import java.io.StringWriter;
13
14import javax.xml.bind.JAXBContext;
15import javax.xml.bind.JAXBException;
16import javax.xml.bind.Marshaller;
17
18import org.dom4j.Document;
19import org.dom4j.DocumentException;
20import org.dom4j.DocumentHelper;
21import org.dom4j.Node;
22
23public 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}
130
131
1
2 1 XmlUtil的一个使用事例如下所示:
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 1 /**
2 *@Description: 章节列表搜索结果
3 */
4package com.lulei.test;
5
6import java.util.ArrayList;
7
8import javax.xml.bind.annotation.XmlRootElement;
9
10import com.lulei.util.XmlUtil;
11
12@XmlRootElement(name = "root")
13public 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}
42
43
1
2 1 运行结果如下图所示(数据经过格式话处理):
2
在XmlUtil类中使用到了CharsetUtil类,关于CharsetUtil类在以后的博客中再详细介绍(主要作用就是检测文件或者流的编码方式等)。
ps:最近发现其他网站可能会对博客转载,上面并没有源链接,如想查看更多关于 基于lucene的案例开发 请 点击这里。或访问网址http://blog.csdn.net/xiaojimanman/article/category/2841877