在网上搜索了一番发现用json-lib进行json格式转换的还真不少,但是经过测试性能不太令人满意,同类工具中还有个后起

之秀那就是jackson,单从性能上说要比json-lib好很多,于是在项目中就决定用jackson了。
     但是关于jackson的资料在网上相比不是很多,于是到了官方网站看了看,把源码下载下来。帮助文档做的不太好,也没有

个现成的例子供参考。不过还好,最后在官方网站的某个角落里找到了一些例子, 我在原来例子的基础上稍加改动封装了一个工具,供网友们参考,有不当之处还望拍砖指正。

      为性能考虑尽量少的向客户端发送数据,所以在Bean到JSON转换的时候把不需要的字段过滤掉,要完成这个功能我们必须自定义一个实现StdSerializerProvider接口的序列化器BzStdSerializerProvider,然后把这个序列化器赋给ObjectMapper即可,下面就把整个具体实现贴出来:

view plaincopy to clipboardprint?

1. package
2. import
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10. import
11. import
12. import
13. import
14. import
15. import
16. import
17. import
18. /** 
19.  
20.  
21.  
22.  
23.   
24. public class
25. private static final ObjectMapper mapper = new
26. static class FilteredWriter extends
27. public
28. super(w);  
29.         }  
30. public void
31. throws
32.             BzStdSerializerProvider myprov = (BzStdSerializerProvider) prov;  
33.             HashMap<?, ?> filter = myprov.getCurrentFilter();  
34. if (filter == null) {  
35. super.serializeAsField(bean, jgen, prov);  
36. else if (filter.containsKey(this._name)) {  
37. this._name);  
38. class.isAssignableFrom(subfilter  
39. null);  
40. super.serializeAsField(bean, jgen, prov);  
41.                 myprov.popFilter();  
42.             }  
43.         }  
44.     }  
45. static class CustomBeanFactory extends
46.     {  
47. @Override
48. protected
49.                 BasicBeanDescription beanDesc, BeanSerializer ser,  
50.                 List<BeanPropertyWriter> props) {  
51. super.processViews(config, beanDesc, ser, props);  
52.             BeanPropertyWriter[] writers = props  
53. new
54. for (int i = 0; i < writers.length; ++i) {  
55. new
56.             }  
57.             ser = ser.withFiltered(writers);  
58. return
59.         }  
60.     }  
61. static class BzStdSerializerProvider extends
62. private
63. private Vector<HashMap<?, ?>> _stack = new
64. public
65. super();  
66.         }  
67. public
68. super();  
69.             _filter = filter;  
70.         }  
71. protected
72.                 StdSerializerProvider src, SerializerFactory f) {  
73. super(config, src, f);  
74.         }  
75. protected
76.                 StdSerializerProvider src, SerializerFactory f,  
77.                 HashMap<?, ?> filter) {  
78. super(config, src, f);  
79.             _filter = filter;  
80.         }  
81. protected
82.                 SerializationConfig config, SerializerFactory jsf) {  
83. return new BzStdSerializerProvider(config, this, jsf, _filter);  
84.         }  
85. public
86. if
87. return
88. return
89.         }  
90. public void
91.             _stack.add(filter);  
92.         }  
93. public void
94. if
95.                 _stack.removeElement(_stack.lastElement());  
96.             }  
97.         }  
98.     }  
99. /**
100.  
101.  
102.  
103.  
104.   
105. public static
106. try
107. if (bean != null && filter != null) {  
108.                 HashMap<?, ?> filterMap = mapper.readValue(filter,  
109. class);  
110. new
111.                         filterMap));  
112. new
113. return mapper.viewWriter(String.class).writeValueAsString(bean);  
114.             }  
115. catch
116.             e.printStackTrace();  
117. catch
118.             e.printStackTrace();  
119. catch
120.             e.printStackTrace();  
121.         }  
122. return null;  
123.     }  
124. /**
125.  
126.  
127.  
128.  
129.   
130. public static
131. try
132. if (bean != null && filter != null) {  
133.                 HashMap<?, ?> filterMap = mapper.readValue(filter,  
134. class);  
135. new
136.                         filterMap));  
137. new
138. return mapper.viewWriter(String.class).writeValueAsString(bean);  
139.             }  
140. catch
141.             e.printStackTrace();  
142. catch
143.             e.printStackTrace();  
144. catch
145.             e.printStackTrace();  
146.         }  
147. return null;  
148.     }  
149. /**
150.  
151.  
152.  
153.   
154. public static
155. try
156. if (bean != null) {  
157. return
158.             }  
159. catch
160.             e.printStackTrace();  
161. catch
162.             e.printStackTrace();  
163. catch
164.             e.printStackTrace();  
165.         }  
166. return null;  
167.     }  
168. }

上述类只是一个实现过滤功能的Bean to Json的工具类,当然你也可以继续扩展。下面我们继续完善,提供一个综合的,支持过滤的,能JSON互转的,转换内容以及方法能自定义的一个综合JSON转换工具,当然要有上边的类做支持了。这是一个基于接口的动态代理的实现,

具体代码如下。

view plaincopy to clipboardprint?

1. package
2.   
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10. import
11. import
12. import
13. import
14. import
15. import
16. import
17. import
18. import
19. import
20.   
21. public class
22. private
23. public static
24. new
25. return
26.         }  
27. public static
28.             ClassLoader classLoader = Thread.currentThread().getContextClassLoader();  
29. if (classLoader == null) classLoader = type.getClassLoader();  
30. new Class<?>[additionalTypes.length + 1];  
31. 0] = type;  
32. 0, interfaces, 1, additionalTypes.length);  
33. new
34.             Object proxy = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);  
35. return
36.         }  
37. public static
38.             InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy);  
39. if (invocationHandler instanceof
40.                 JsonInvocationHandler jsonInvocationHandler = (JsonInvocationHandler) invocationHandler;  
41. return
42.             }  
43. throw new IllegalArgumentException("Proxy is not a JacksonProxy");  
44.         }  
45. public static class JsonInvocationHandler implements
46. private final
47. private final Map<Method, Handler> handlers = new
48. public
49. if (objectMapper == null) throw new NullPointerException("mapper is null");  
50. if (interfaces == null) throw new NullPointerException("type is null");  
51. this.objectMapper = objectMapper;  
52. for
53. for
54.                         String name = method.getName();  
55.                         Class<?>[] parameterTypes = method.getParameterTypes();  
56.                         Class<?> returnType = method.getReturnType();  
57. if (name.startsWith("read")) {  
58. if (parameterTypes.length == 1
59. new
60.                                 handlers.put(method, handler);  
61.                             }  
62. else if (name.startsWith("write")) {  
63. if
64. new WriteHandler(objectMapper, null, canThrowIOException(method));  
65.                                 handlers.put(method, handler);  
66. else{  
67. new
68.                                 handlers.put(method, handler);  
69.                             }  
70.                         }  
71.                     }  
72.                 }  
73.             }  
74. public
75. return
76.             }  
77. @Override
78. public Object invoke(Object proxy, Method method, Object[] args) throws
79.                 Handler handler = handlers.get(method);  
80. if (handler == null) {  
81. throw new
82.                 }  
83. return
84.             }  
85. private static boolean
86. for
87. if (IOException.class.isAssignableFrom(exceptionType)) {  
88. return true;  
89.                     }  
90.                 }  
91. return false;  
92.             }  
93.         }  
94. private static interface
95. throws
96.         }  
97. private static class ReadHandler implements
98. private final
99. private final
100. private final boolean
101. public ReadHandler(ObjectMapper mapper, Type type, boolean
102. this.mapper = mapper;  
103.                 javaType = TypeFactory.fromType(type);  
104. this.canThrowIoException = canThrowIoException;  
105.             }  
106. @Override
107. public Object invoke(Object[] args) throws
108. try
109. 0];  
110. return
111. catch
112. if
113. throw
114. else
115. throw new
116.                     }  
117.                 }  
118.             }  
119. public Object read(Object source) throws
120. if (source == null) {  
121. throw new NullPointerException("source is null");  
122.                 }  
123.                 JsonParser parser;  
124. if (source instanceof
125.                     String string = (String) source;  
126.                     parser = mapper.getJsonFactory().createJsonParser(string);  
127. else if (source instanceof byte[]) {  
128. byte[] bytes = (byte[]) source;  
129.                     parser = mapper.getJsonFactory().createJsonParser(bytes);  
130. else if (source instanceof
131.                     Reader reader = (Reader) source;  
132.                     parser = mapper.getJsonFactory().createJsonParser(reader);  
133.                     parser.disableFeature(JsonParser.Feature.AUTO_CLOSE_SOURCE);  
134. else if (source instanceof
135.                     InputStream inputStream = (InputStream) source;  
136.                     parser = mapper.getJsonFactory().createJsonParser(inputStream);  
137.                     parser.disableFeature(JsonParser.Feature.AUTO_CLOSE_SOURCE);  
138. else if (source instanceof
139.                     File file = (File) source;  
140.                     parser = mapper.getJsonFactory().createJsonParser(file);  
141. else if (source instanceof
142.                     URL url = (URL) source;  
143.                     parser = mapper.getJsonFactory().createJsonParser(url);  
144. else
145. throw new UnsupportedOperationException("Unsupported source type " + source.getClass() + " for JSON read method");  
146.                 }  
147. try
148. return
149. finally
150.                     parser.close();  
151.                 }  
152.             }  
153.         }  
154. private static class WriteHandler implements
155. private final
156. private final
157. private final boolean
158. public WriteHandler(ObjectMapper mapper, Class<?> returnType, boolean
159. this.mapper = mapper;  
160. this.returnType = returnType;  
161. this.canThrowIoException = canThrowIoException;  
162.             }  
163. @Override
164. public Object invoke(Object[] args) throws
165. try
166. 0];  
167. if (returnType == null) {  
168. 1];  
169.                         write(value, target);  
170. return null;  
171. else if (String.class.equals(returnType)) {  
172. if (args.length>=2&&args[1]!=null) {//如果返回类型是String且有第二个参数,那么就默认第二个参数为过滤参数
173. return CustomSerialization.writeBean(value, args[1].toString());  
174. else
175. new
176.                             write(value, stringWriter);  
177. return
178.                         }  
179. else if (byte[].class.equals(returnType)) {  
180. new
181.                         write(value, out);  
182. return
183. else
184. throw new UnsupportedOperationException("Unsupported target type " + returnType + " for JSON write method");  
185.                     }  
186. catch
187. if
188. throw
189. else
190. throw new
191.                     }  
192.                 }  
193.             }  
194. public void write(Object value, Object target) throws
195. if (target == null) {  
196. throw new NullPointerException("target is null");  
197.                 }  
198.                 JsonGenerator generator;  
199. if (target instanceof
200.                     Writer writer = (Writer) target;  
201.                     generator = mapper.getJsonFactory().createJsonGenerator(writer);  
202.                     generator.disableFeature(JsonGenerator.Feature.AUTO_CLOSE_TARGET);  
203. else if (target instanceof
204.                     OutputStream outputStream = (OutputStream) target;  
205.                     generator = mapper.getJsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);  
206.                     generator.disableFeature(JsonGenerator.Feature.AUTO_CLOSE_TARGET);  
207. else if (target instanceof
208.                     File file = (File) target;  
209.                     generator = mapper.getJsonFactory().createJsonGenerator(file, JsonEncoding.UTF8);  
210. else
211. throw new UnsupportedOperationException("Unsupported target type " + target.getClass() + " for JSON write method");  
212.                 }  
213. if
214.                     generator.useDefaultPrettyPrinter();  
215.                 }  
216.                   
217. try
218.                     mapper.writeValue(generator, value);  
219. finally
220.                     generator.close();  
221.                 }  
222.             }  
223.         }  
224. }

接口代码:

 

view plaincopy to clipboardprint?

1. package
2. import
3. import
4. import
5. import
6. import
7. import
8. import
9.   
10.  public  interface JsonInterface {  
11. throws
12. int
13.     Integer readInteger(String value);  
14.     Object readBean(String value);  
15. throws
16. int[] readIntArray(String value);  
17.     List<Integer> readIntegerList(String value);  
18.       
19.     List<Short> readShortList(String value);  
20.       
21.     List<Object> readBeanList(String value);  
22.       
23.     List<Map<String,Object>> readBeanByMap(String value);  
24. byte[] value);  
25.     List<Object> readBeanList(Reader value);  
26.     List<Object> readBeanList(InputStream value);  
27. throws
28. int
29.     String writeInteger(Integer value);  
30.     String writeBean(Object value);  
31.       
32.     String writeBean(Object value,String filter);  
33. throws
34. int[] value);  
35.     String writeIntegerList(List<Integer> value);  
36.     String writeBeanList(List<?> value);  
37.       
38.     String writeBeanList(List<?> value,String filter);  
39. void
40. void
41. byte[] writeBeanListToByteArray(List<?> value);  
42. }

最终供调用的工具代码:

view plaincopy to clipboardprint?

1. package
2. import
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10. import
11. import
12. import
13.   
14. /** 
15.  
16.  
17.  
18.  
19.   
20.  public class JsonUtil{  
21. private static
22. static{  
23. new
24. true);  
25. class);  
26.     }  
27. public static
28. return
29.     }  
30.       
31. //**********************************************************************************  
32. static class
33.        {  
34. public
35. public
36. public
37. public
38. public
39. public
40. this.name = name;  
41. this.value = value;  
42. this.secret = secret;  
43. new
44.            }  
45.        }  
46. static class
47.        {  
48. public  long  id = 123;  
49. public String name = "child";  
50. public String address = "123 Street";  
51.        }  
52. public static void main(String[] args) throws
53. new ViewBean("mr bean", null, "secret!");  
54. new ViewBean("sibling", "lala", "boooo");  
55.         String  filter = "{\"name\":0,\"value\":0,\"sibling\":{\"name\":0}, \"child\":{\"id\":0,\"address\":0}}";  
56.           
57.         System.out.println(json.writeBean(bean,filter));  
58.     }  
59. }

这样实现的一个好处就是方法可以自定义,向把json串转换成什么类型的bean只要在JsonInterface接口中申明就可以了。这个是基于

jackson1.5版本实现的。