• JSON与Java对象的互相转换


    JSON与Java对象的互相转换

    • 例一(单个对象进行赋值):

        @RequestMapping("test1.do")
        @ResponseBody
        public JSONObject test1(HttpServletRequest request, HttpServletResponse response) {
        	JSONObject jsonObject = new JSONObject();
        	jsonObject.put("key1", "value1");
        	jsonObject.put("key2", "value2");
        	jsonObject.put("key3", "value3");
        	return jsonObject;
        }
      
    • 例二(多个对象进行转换):

        @RequestMapping("TestListQrcode.do")
        @ResponseBody
        public JSONObject TestListQrcode(HttpServletRequest request, HttpServletResponse response)
        	throws Exception {
        	//String user_phone = request.getParameter("user_phone");
        	String user_phone ="13652458975";
        
        	Qrcode qrcode = new Qrcode();
        	qrcode.setUser_phone(user_phone);
        	qrcode.setQrcode_type("普通型");
        	List<Qrcode> list  = qrcodeService.selectQrcodeList(qrcode);
      
       	 	//创建json集合
       		 //用的包:import net.sf.json.JSONArray;
       	 	JSONArray jsonArray = JSONArray.fromObject(list);
        	System.out.println(jsonArray.toString());
        	JSONObject jsonObject = new JSONObject();
        	jsonObject.put("code", 1);
        	
        	jsonObject.put("data", jsonArray.toString());
        	return jsonObject;
        }
      
    • 例三(字符串的拼接,我只在servlet中用过):

        String value1 = "1";
        int value2 = count-1;
        System.out.println("给前面传的count:"+value2);
        String photo_file = par[0] + "/" + par[1] + "/images";
        //进行拼凑json字符串
        String jsonStr =
        "{" + '"'+ "success" + '"'  +":" + '"' + value1 + '"' + ","
            + '"' + "count" + '"' +":" + '"' + value2 + '"' + ","
            + '"' + "photo_file" + '"' +":" + '"' + photo_file + '"' 
            +"}" ;
        PrintWriter out =null ;
        out =response.getWriter() ;
        out.write(jsonStr);
        out.close();
  • 相关阅读:
    c++11——列表初始化
    flask学习(十二):for循环遍历
    flask学习(十一):if判断语句
    flask学习(十):模板中访问模型和字典的属性
    flask学习(九):模板渲染和参数传递
    flask学习(八):页面跳转和重定向
    flask学习(七):URL反转
    flask学习(六):URL传参
    flask学习(五):使用配置文件
    flask学习(四):debug模式
  • 原文地址:https://www.cnblogs.com/renxiuxing/p/9977754.html
Copyright © 2020-2023  润新知