項目用到的Json字串到Json對象轉換 – JAVA編程語言程序開發技術文章

如下代碼:
[java]
StringBuilder sb = new StringBuilder("["); 
sb.append("{"); 
sb.append("cremindTitle:\"小名\","); 
sb.append("cremindDate:\"2012-06-05 19:20:22\","); 
sb.append("cremindRemark:\"阿斯蒂芬\""); 
sb.append("}"); 
sb.append("]"); 
List<Cremind> clist = JSONArray.toList(JSONArray.fromObject(sb.toString()), 
        Cremind.class); 

在執行中會報錯,原因是由於日期類型字串到日期類型Timestamp的轉換,解決思路如下:
編寫一個Morpher類繼承自AbstractObjectMorpher
[java] 
class TimeStampMorpher extends AbstractObjectMorpher{ 
     
    private Logger LOG = Logger.getLogger(TimeStampMorpher.class); 
     
    private String format ="yyyy-MM-dd hh:mm:ss"; 
    public void setFormat(String format) { 
        this.format = format; 
    } 
     
    public TimeStampMorpher() { 
        // TODO Auto-generated constructor stub 
    } 
     
    public TimeStampMorpher(String format) { 
        this.format = format; 
    } 
 
    @Override 
    public Object morph(Object dateStr) { 
        // TODO Auto-generated method stub 
         
        try {        
            java.util.Date date = new SimpleDateFormat(format).parse(dateStr.toString()); 
            return new Timestamp(date.getTime()); 
        } catch (ParseException e) { 
            // TODO Auto-generated catch block 
            if (LOG.isInfoEnabled()) 
                LOG.info("日期格式可能無效,將采用系統當前日期"); 
            e.printStackTrace(); 
        } 
        return new  java.sql.Timestamp(System.currentTimeMillis());//返回默認日期      
    } 
 
    @Override 
    public Class morphsTo() { 
        // TODO Auto-generated method stub 
        return Timestamp.class; 
    } 

最終處理版本:
[java] 
package com.defshare.foundation.global; 
 
import java.sql.Timestamp; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.List; 
 
import org.apache.log4j.Logger; 
 
import net.sf.ezmorph.object.AbstractObjectMorpher; 
import net.sf.json.JSONArray; 
import net.sf.json.util.JSONUtils; 
 
class TimeStampMorpher extends AbstractObjectMorpher{ 
     
    private Logger LOG = Logger.getLogger(TimeStampMorpher.class); 
     
    private String format ="yyyy-MM-dd hh:mm:ss"; 
    public void setFormat(String format) { 
        this.format = format; 
    } 
     
    public TimeStampMorpher() { 
        // TODO Auto-generated constructor stub 
    } 
     
    public TimeStampMorpher(String format) { 
        this.format = format; 
    } 
 
    @Override 
    public Object morph(Object dateStr) { 
        // TODO Auto-generated method stub 
         
        try {        
            java.util.Date date = new SimpleDateFormat(format).parse(dateStr.toString()); 
            return new Timestamp(date.getTime()); 
        } catch (ParseException e) { 
            // TODO Auto-generated catch block 
            if (LOG.isInfoEnabled()) 
                LOG.info("日期格式可能無效,將采用系統當前日期"); 
            e.printStackTrace(); 
        } 
        return new  java.sql.Timestamp(System.currentTimeMillis());//返回默認日期      
    } 
 
    @Override 
    public Class morphsTo() { 
        // TODO Auto-generated method stub 
        return Timestamp.class; 
    } 

 
public final class JsonUtil { 
     
    /**
     * json數組字串到json數組對象<br/>
     * <pre>
     *  StringBuilder sb = new StringBuilder("[");
     *  sb.append("{");
     *  sb.append("cremindTitle:\"xiaoqiang\",");
     *  sb.append("cremindDate:\"2012-06-0519:20:22\",");
     *  sb.append("cremindRemark:\"xiaoqiangremark\"");
     *  sb.append("}");
     *  sb.append("]");
     * </pre>
     * @param jsonArray
     * @param classzz
     */ 
    public static final <T>  List<T>  jsonArrayToList(String jsonArray,Class classzz){ 
        JSONUtils.getMorpherRegistry().registerMorpher(new TimeStampMorpher()); 
//      JSONUtils.getMorpherRegistry().registerMorpher(new TimeStampMorpher());         
//      StringBuilder sb = new StringBuilder("["); 
//      sb.append("{"); 
//      sb.append("cremindTitle:\"小名\","); 
//      sb.append("cremindDate:\"2012-06-0519:20:22\","); 
//      sb.append("cremindRemark:\"阿斯蒂芬\""); 
//      sb.append("}"); 
//      sb.append("]"); 
//      List<Cremind> clist = JSONArray.toList(JSONArray.fromObject(sb.toString()), 
//              Cremind.class); 
         
        return JSONArray.toList(JSONArray.fromObject(jsonArray),classzz); 
    } 
 

項目中表示層Action調用:
[java]
/**
     * 新增客戶
     * 請求參數:
     * name:客戶名稱
     *  cno:客戶編號(跟ID不同)
     *  customKindId:客戶性質ID
     *  phone:公司電話
     *  fax:公司傳真
     *  address:客戶地址
     *  siteUrl:公司網址
     *  cIndustryId:客戶行業ID
     *  cIndustryNum:行業排名
     *  mainSellProduct:主營產品
     *  cbuildDate:成立時間
     *  clevelId:客戶級別ID
     *  signTag:簽約標志
     *  remind:[{
     *  cremindTitle:提醒名稱
     *  cremindDate:提醒日期
     *  cremindRemark:備註
     *  },{},{}]
     * @return
     * @throws Exception
     */ 
    public String addCustomer() throws Exception{ 
        return super.executeAction(new IExecuteActionCallback() { 
             
            public String execute(BaseJSONAction baseJsonAction) { 
                Customer cst = new Customer(); 
                bindParam2Bean(cst);//綁定請求參數到對象 
                //處理特殊參數的綁定 
                //處理客戶性質ID 
                String customKindId = getParam("customKindId").toString(); 
                if (!StringUtils.isBlank(customKindId)){ 
                    CustomKind ck = new CustomKind(); 
                    ck.setCustomKindId(Integer.valueOf(customKindId)); 
                    cst.setCustomKind(ck);                   
                } 
                 
                //處理客戶行業 
                String cIndustryId = getParam("cIndustryId").toString(); 
                if(!StringUtils.isBlank(cIndustryId)){ 
                    Cindustry cs = new Cindustry(); 
                    cs.setCindustryId(Integer.valueOf(cIndustryId)); 
                    cst.setCindustry(cs); 
                } 
                //處理客戶級別 
                String clevelId = getParam("clevelId").toString(); 
                if(!StringUtils.isBlank(clevelId)){ 
                    Clevel cl = new Clevel(); 
                    cl.setClevelId(Integer.valueOf(clevelId)); 
                    cst.setClevel(cl); 
                } 
                 
                //處理註冊時間 
                cst.setCregArchDate(DateUtil.getTimestamp()); 
                if (cst.getCbuildDate()==null) 
                    cst.setCbuildDate(DateUtil.getTimestamp()); 
                 
                //處理所屬員工 
                Emp emp = getCurrentUser(); 
                if (emp!=null) 
                    cst.setEmp(emp); 
                                 
                 
                <span style="color:#3366ff;">//處理提醒 
                String remind = getParam("remind").toString(); 
                //反序列化JSON字符串到對象數組 
                //List<Cremind> clist = JSONArray.toList(JSONArray.fromObject(remind),Cremind.class); 
                List<Cremind> clist = JsonUtil.jsonArrayToList(remind, Cremind.class);</span> 
                //設置客戶提醒 
                cst.setCreminds(new HashSet(clist)); 
                 
                cstService.addCustomer(cst);                 
                 
                return SUCCESS; 
            } 
        }); 
    } 

作者:jiangtongcn

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *