使用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、double、int、long、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;
}