使用JSONObject解析和生成json

建立JSON

引用org.json包,推薦經過maven引用json

一、直接構建數組

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類型存儲。

二、使用HashMap構建app

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());   

 三、使用JavaBean構建(經常使用,代碼重用率高)maven

//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),以此類推。this

數組的解析麻煩一點,須要經過JSONObject對象的getJSONArray(key)方法獲取到一個JSONArray對象,再調用JSONArray對象的get(i)方法獲取數組元素,i爲索引值spa

@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;}
相關文章
相關標籤/搜索