zoukankan      html  css  js  c++  java
  • 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);
            
           
  • 相关阅读:
    2010年度最有技术含量攻击:Padding Oracle Attack 狼人:
    微软宣布最新企业安全产品FEP 免费试用 狼人:
    金山卫士开放第三批源代码 ARP防火墙可下载 狼人:
    Gawker攻击事件暴露密码保护缺陷 狼人:
    Win7和Mac及HTML5将成黑客2011年攻击重点 狼人:
    开发人员发现Chrome浏览器漏洞获谷歌重奖 狼人:
    FBI被指在OpenBSD的IPSEC协议栈中放置后门 狼人:
    微软发布重大安全忧患警告或影响全球9亿用户 狼人:
    MHTML中曝出0day漏洞 影响各版Windows 狼人:
    nullnullCSharp Tools Compiler
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/4732046.html
Copyright © 2011-2022 走看看