JSON 字符串 与 java 对象的转换

jsonLib 经典文章:http://json-lib.sourceforge.net/xref-test/net/sf/json/TestJSONObject.html

// 引入相应的包 json-lib-2.2.3.jar

 

对象转json:

 

        IorderIssue iorderIssue = new IorderIssue();
        
        SegmentInfo segmentInfo = new SegmentInfo();
        segmentInfo.setIorderIssue(iorderIssue);
        List<SegmentInfo> list = new ArrayList<SegmentInfo>();
        list.add(segmentInfo);
        iorderIssue.setSegmentInfos(list);
        
        List<ReqPassenger> list1 = new ArrayList<ReqPassenger>();
        ReqPassenger reqPassenger = new ReqPassenger();
        reqPassenger.setBusinessNo("111");
        reqPassenger.setIorderIssue(iorderIssue);
        list1.add(reqPassenger);
        iorderIssue.setReqPassengers(list1);
        
        
        JsonConfig conf = new JsonConfig();
        conf.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        JSONObject object = JSONObject.fromObject(iorderIssue,conf);

其中conf.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);可防止hibernate模式下的关联关系子对象中包含父对象造成死循环。

json转对象:

 

1.这个方法 JSONSerializer.toJava();

    /**
     * 创建订单
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView createOrder(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String requestStr = MyString.inputStream2String(request.getInputStream());
        
        JsonConfig filterNullConfig = new JsonConfig();//先把为null的属性过滤掉,防止下边的日期转换报错
        filterNullConfig.setJsonPropertyFilter(new PropertyFilter() {
            
            public boolean apply(Object clazz, String name, Object value) {
                boolean isFilter = false;
                if(value==null||"".equals(value)){
                    isFilter = true;
                }
                return isFilter;
            }
        });
        JSONObject requestJson = JSONObject.fromObject(requestStr,filterNullConfig);
    

        try{
            //日期转换
            String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM-dd HH:mm"};    
            JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats)); 

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setRootClass(IorderIssue.class);
            Map<String, Class> classMap = new HashMap<String, Class>();
            classMap.put("iordersegments", IorderSegment.class);
            classMap.put("iorderpassengers", IorderPassenger.class);
            jsonConfig.setClassMap(classMap);

            IorderIssue iorderIssue = (IorderIssue)JSONSerializer.toJava(requestJson,jsonConfig);
            iorderIssue.setCreateTime(new Date());
            
            iorderIssue.setOrderType("01");//出票订单
            String isAduting = iorderIssue.getIsAduting();
            if("1".equals(isAduting)){
                iorderIssue.setOrderStatus("000");//待审核
            }else if("0".equals(isAduting)){
                iorderIssue.setOrderStatus("001");//待支付
            }
            
            IorderPriceIssue iorderPriceIssue = iorderIssue.getIorderPriceIssue();
            

        
            String orderId = iorderIssueManager.saveIorderIssue(iorderIssue, iorderPriceIssue,user);
            
            if(MyString.isNoEmpty(orderId)){//如果返回id,保存行程单信息
                IorderJourneyInfo iorderJourneyInfo = iorderIssue.getIorderJourneyInfo();
                iorderJourneyInfo.setBusinessId(orderId);
                this.universalManager.save(iorderJourneyInfo);
            }

            
            MyJSONTools.responseWriteData(response, "OKφ"+orderId);
        }catch(Exception e){
            e.printStackTrace();
            MyJSONTools.responseWriteData(response, "error:"+e.getMessage());
        }
        return null;
    }

 

 


2.

jsonWorkflowBean是json字符串

// 转换成Json对象
            JSONObject jsonObj = JSONObject.fromObject(jsonWorkflowBean);/*
             * 在JSONObject.toBean的时候如果转换的类中有集合,可以先定义Map<String, Class> classMap
             * = new HashMap<String,
             * Class>();在classMap中put你要转换的类中的集合名,像:classMap.put("teachers",
             * Teacher.class);然后在toBean()的时候把参数加上, 像:Student student=(Student)
             * JSONObject.toBean(str, Student.class, classMap);
             */
            Map<String, Class> classMap = new HashMap<String, Class>();
            classMap.put("inputDataList", InputDataBean.class);
            classMap.put("imageList", ImageBean.class);
            //将json转换成workflowBean
            WorkflowBean workflow = (WorkflowBean) JSONObject.toBean(jsonObj,
                    WorkflowBean.class, classMap);

 

 

jsonarray转list:

        JSONObject requestJson = JSONObject.fromObject(requestStr);
        
        String reqPassengers = requestJson.getString("reqPassengers");
        
        Map<String, Class> classMap = new HashMap<String, Class>();
        classMap.put("reqPassengers", ReqPassenger.class);
        
        JSONArray jsonArray = JSONArray.fromObject(reqPassengers);
        
        List<ReqPassenger> list = (List<ReqPassenger>)JSONArray.toCollection(jsonArray);
        
       

 

posted @ 2015-08-15 11:28  新手娃娃菜  阅读(458)  评论(0编辑  收藏  举报