博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JSON字符串

Posted on 2017-09-18 13:57  亡者归来19  阅读(154)  评论(0)    收藏  举报
public static void main(String[] args) {
        TestJsonBean();
    }
    //java对象与json对象相互转换
    public static void TestJsonBean(){
        Student stu=new Student();
        
        stu.setId(1);
        stu.setName("吴彦祖");
        stu.setSex("男");
        stu.setAge(30);
        stu.setHobby(new String[]{"游泳","跑步","上山","打飞机"});
        //java对象转成json对象,并获取json对象属性
        JSONObject jso=JSONObject.fromObject(stu);
        System.out.println(jso.toString());
        System.out.println(jso.getInt("id"));
        System.out.println(jso.getString("name"));
        System.out.println(jso.getString("sex"));
        System.out.println(jso.getInt("age"));
        System.out.println(jso.getJSONArray("hobby"));
        
        //java对象与json对象相互转换
        Student student=(Student)JSONObject.toBean(jso, Student.class);
        System.out.println(student.getId());
        System.out.println(student.getName());
        System.out.println(student.getSex());
        System.out.println(student.getAge());
        System.out.println(student.getHobby());
        
        //创建json对象
        JSONObject jsob=new JSONObject();
        jsob.put("id", 2);
        jsob.put("name", "陈冠希");
        jsob.put("sex", "男");
        jsob.put("age", 30);
        jsob.put("hobby", new String[]{"打飞机","约炮","斗地主" });
        
        //json对象转换成java对象
        Student so=(Student)JSONObject.toBean(jsob, Student.class);
        System.out.println(so.getName());
        System.out.println(so.getId());
        System.out.println(so.getSex());
        System.out.println(so.getAge());
        System.out.println(so.getHobby());
        
        
    }
    
    public static void TestJsonArray(){
        Student stu=new Student();
        stu.setId(3);
        stu.setName("邓超");
        stu.setSex("男");
        stu.setAge(32);
        stu.setHobby(new String[]{"逗比","SB"});
        
        
        Student stu1=new Student();
        stu1.setId(4);
        stu1.setName("李晨");
        stu1.setSex("男");
        stu1.setAge(35);
        stu1.setHobby(new String[]{"范冰冰","SB"});
        
        List<Student> lis=new ArrayList<Student>();
        lis.add(stu);
        lis.add(stu1);
        
        //把集合转成JSONArray
        JSONArray js=JSONArray.fromObject(lis);
        for(int i=0; i<js.size();i++){
            JSONObject f=(JSONObject)js.get(i);
            System.out.println(f.getInt("id"));
            System.out.println(f.getString("name"));
            System.out.println(f.getString("sex"));
            System.out.println(f.getInt("age"));
            System.out.println(f.getJSONArray("hobby"));
        }
    }