• 使用JSONObject解析和生成json


    创建JSON

    引用org.json包,推荐通过maven引用

    1、直接构建

    JSONObject obj = new JSONObject();
    obj.put("sex", "male");
    obj.put("age", 22);
    obj.put("is_student", true);
    obj.put("hobbies", new String[] {"hiking", "swimming"});
    
    //调用toString()方法可直接将其内容打印出来
    System.out.println(obj.toString());
    
    结果:
    {"hobbies":["hiking","swimming"],"sex":"male","name":"John","is_student":true,"age":22}
    key值必须为String类型, value可以为boolean、doubleintlong、Object、Map以及Collection等。
    当然,double以及int等类型只是在Java中,写入到json中时,统一都会以Number类型存储。

    2、使用HashMap构建

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("name", "John");
    data.put("sex", "male");
    data.put("age", 22);
    data.put("is_student", true);
    data.put("hobbies", new String[] {"hiking", "swimming"});
    JSONObject obj = new JSONObject(data);
    System.out.println(obj.toString());   

     3、使用JavaBean构建(常用,代码重用率高)

    //JavaBean
    public class PersonInfo {
        private String name;
        private String sex;
        private int age;
        private boolean isStudent;
        private String[] hobbies;  
        public void setName(String name) {
            this.name = name;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public void setStudent(boolean isStudent) {
            this.isStudent = isStudent;
        }
        public void setHobbies(String[] hobbies) {
            this.hobbies = hobbies;
        }
        //getter不能少
        public String getName() {
            return name;
        }
        public String getSex() {
            return sex;
        }
        public int getAge() {
            return age;
        }
        public boolean isStudent() {
            return isStudent;
        }
        public String[] getHobbies() {
            return hobbies;
        }
    }
    
    //Main
    import org.json.JSONObject;
    public class JSONObjectSample {
        public static void main(String[] args) {
            createJsonByJavaBean();
        }
        private static void createJsonByJavaBean() {
            PersonInfo info = new PersonInfo();
            info.setName("John");
            info.setSex("male");
            info.setAge(22);
            info.setStudent(true);
            info.setHobbies(new String[] {"hiking", "swimming"});      
            JSONObject obj = new JSONObject(info);
            System.out.println(obj);
        }
    }

    解析JSON

    基本类型的解析直接调用JSONObject对象的getXxx(key)方法,如果获取字符串则getString(key),以此类推。

    数组的解析麻烦一点,需要通过JSONObject对象的getJSONArray(key)方法获取到一个JSONArray对象,再调用JSONArray对象的get(i)方法获取数组元素,i为索引值

    @RequestMapping("/view")
    public ModelAndView user(HttpServletRequest request,User user){
         String path = request.getParameter("path") + "";
         String contextPath = request.getContextPath();
         ModelAndView mav = new ModelAndView();
         JSONObject jsonObj = new JSONObject();
         jsonObj = userService.getGroupList(user);
    
         //判断JSON是否存在error_msg,存在则请求失败,返回错误信息
       if(jsonObj.has("error_msg")){          
           String error_msg = (String) jsonObj.get("error_msg");
             mav.addObject("msg",error_msg );
         }else{//解析JSON,获取用户组列表
             //Integer result_num= jsonObj.getInt("result_num");//返回结果数 
             JSONArray result = jsonObj.getJSONArray("result"); 
             String resStr = result.toString();
             resStr = resStr.replace("[", "").replace("]", "").replace(""", "");
             String[] groupList = resStr.split(",");
             mav.addObject("groupList", groupList);
         }
         mav.addObject("contextPath", contextPath);
         mav.setViewName(path);
         return mav;
    }

     

     

     

     

  • 相关阅读:
    Python pip离线部署
    Windows API 纳秒级别延迟
    基于Cython和内置distutils库,实现python源码加密(非混淆模式)
    boost.property_tree读取中文乱码问题
    Direct初始化三步曲
    分享一个电子发票信息提取工具(Python)
    关于&0x80
    给QT不规则窗口添加阴影
    waveout系列API实现pcm音频播放
    An application has made an attempt to load the C runtime library incorrectly.Please contact the application's support te
  • 原文地址:https://www.cnblogs.com/whatarewords/p/10774543.html
Copyright © 2020-2023  润新知