Jackson 2.0用法
json-lib轉換復雜數據結構時,老是報異常,轉用到Jackson,現在是2.6.4,網上教程大部分是1.x,這里簡單描述一下2.0的用法,只有bean轉json,其他方法請參考官網(http://wiki.fasterxml.com/JacksonInFiveMinutes)
import com.fasterxml.jackson.databind.ObjectMapper;
……
public class SearchAction extends BaseAction {
……
/**
* Open Api: 特定資源檢索開放接口
* @param request
* @param response
*/
public void find_api(HttpServletRequest request, HttpServletResponse response) {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "";
Map<String, Object> map = new HashMap<String, Object>();
boolean success = false;
StringBuffer error = new StringBuffer();
try{
// 必須參數:type key
String type = request.getParameter("type");
String key = request.getParameter("key");
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(key) && key.trim().length() >= 3){
// 根據type到OpenApi/Search分類下獲取對應配置
SearchOpenApi apiBean = this.getSearchService().getApiBeanByType(type.trim());
// 獲取檢索結果
List<SearchBean> dataList = this.getSearchService().findSearchBeansByKeyAndApi(key.trim(), apiBean);
if (null != dataList && dataList.size() > 0) {
//生成指定反饋json
success = true;
map.putAll(this.getSearchBeanListJson(dataList));
} else {
success = false;
error.append("沒有符合條件的記錄!");
}
} else {
success = false;
error.append("參數錯誤!");
}
}catch(Exception e){
LogUtility.logError("find_api error", e);
success = false;
error.append(e.toString());
}
map.put("success", success);
if (!success && error.length() > 0)
map.put("error", error.toString());
try {
jsonString = objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
LogUtility.logError("find_api JsonProcessingException", e);
}
outPut(request,response, jsonString);
}
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!