jsonConfig用法

y_keven發表於2014-04-24

1.先編寫jsonConfig的初始化程式碼

    private JsonConfig jsonConfig;

 

    public action構造方法() {

 

       jsonConfig = new JsonConfig();

       jsonConfig.registerJsonValueProcessor(Date.class, newJsonValueProcessor() {

           private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

 

           @Override

           public Object processObjectValue(String key,Object value, JsonConfig jsonConfig) {

                return this.process(value);

           }

 

           @Override

           public Object processArrayValue(Object value,JsonConfig arg1) {

                return this.process(value);

           }

 

           // 處理Date型別返回的Json數值

           private Object process(Object value) {

                if (value == null) {

                    return "";

                } else if (value instanceof Date)

                    return sdf.format((Date)value);

                else {

                    return value.toString();

                }

           }

       });

       // 不該傳給前臺的欄位

       jsonConfig.setJsonPropertyFilter(new PropertyFilter() {

           public boolean apply(Objectsource, String name, Object value) {

                if (source instanceof RaffleLog) {

                    if ("contact".equals(name)) {

                        return true;

                    }

                }

                return false;

           }

       });

    }

    /**

    * @param response

    * @param returnType

    * @throws IOException

    */

    private voidprintReturnType2Response(HttpServletResponse response, ReturnType<?>returnType) throws IOException {

       response.setCharacterEncoding("UTF-8");

       response.setContentType("application/json;charset=utf-8");

       response.getWriter().print(JSONObject.fromObject(returnType, jsonConfig));

}

 

2.再在需要跳轉的action方法中編寫相應的返回程式碼

ReturnType<Map<String,Integer>> returnType = newReturnType<Map<String, Integer>>();

if(條件){

returnType.setStatus(ReturnType.Status.SUCCESS.getValue());

}else{

       returnType.setStatus(ReturnType.Status.FAIL.getValue());

      }

       returnType.setMsg(sb.toString());

    this.printReturnType2Response(response,returnType);

 

3.一個案例分析:

/**
 *
 * @Title:DocInfoCustomAction.java
 * @Copyright:Copyright (c) 2005
 * @Description:<br>
* @Created on 2014-4-16 上午9:22:25
 * @author 楊凱
 */
public class DocInfoCustomAction extends DispatchAction{
 
    private finalInteger pageSize = 15; // 每頁顯示頁數
 
    Logger logger= Logger.getLogger(DocInfoCustomAction.class);
 
    privateJsonConfig jsonConfig;
 
    publicDocInfoCustomAction() {
 
       jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class,new JsonValueProcessor() {
           private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
 
           @Override
           public Object processObjectValue(String key, Object value, JsonConfigjsonConfig) {
               return this.process(value);
            }
 
           @Override
           public Object processArrayValue(Object value, JsonConfig arg1) {
               return this.process(value);
            }
 
            // 處理Date型別返回的Json數值
           private Object process(Object value) {
               if (value == null) {
                   return "";
                }else if (value instanceof Date)
                   return sdf.format((Date) value);
                else {
                   return value.toString();
                }
            }
        });
        // 不該傳給前臺的欄位
       jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
           public boolean apply(Object source, String name, Object value) {
               if (source instanceof RaffleLog) {
                   if ("contact".equals(name)) {
                       return true;
                   }
                }
               return false;
            }
        });
    }
 
    /**
     * @paramresponse
     * @paramreturnType
     * @throwsIOException
     */
    private voidprintReturnType2Response(HttpServletResponse response, ReturnType<?>returnType) throws IOException {
       response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
       response.getWriter().print(JSONObject.fromObject(returnType,jsonConfig));
    }
    /**
     * 批量刪除操作
     *
     * @parammapping
     * @paramform
     * @paramrequest
     * @paramresponse
     * @return
     * @throwsIOException
     * @throwsAppException
     */
    publicActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequestrequest, HttpServletResponse response) throws IOException, AppException {
 
        Stringids = Tool.getDefaultValue(request, "ids", ""); // 獲取下拉選單的值
       StringBuffer sb = new StringBuffer();
       ReturnType<Map<String, Integer>> returnType = newReturnType<Map<String, Integer>>();
 
        if (ids!= null && !("").equals(ids)) {
            try {
               String[] idds = ids.split(",");
               for (String id : idds) {
                   int flag = DocInfoTempletApi.deleteDocInfoCustom(id);
                   sb.append("ID為:" + id);
                   if (flag == 1) {
                       sb.append(" 的記錄刪除成功!");
                   } else {
                       sb.append(" 的記錄刪除失敗!");
                   }
                   sb.append("\r\n");
                }
            }catch (Exception e) {
               logger.debug("DocInfoCustomAction.delete():" + e);
            }
           returnType.setStatus(ReturnType.Status.SUCCESS.getValue());
        } else {
           sb.append("條件id不能為空");
           returnType.setStatus(ReturnType.Status.FAIL.getValue());
        }
       returnType.setMsg(sb.toString());
       this.printReturnType2Response(response, returnType);
        returnnull;
    }
}