更新时间:2021年03月18日 08时58分11秒 来源:黑马程序员
使用jsonlib可以将javaBean和json进行相互转化
将一个对象转化成一个json字符串,如下:
Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("北京市西城区");        //1)使用JSONObject
        JSONObject json = JSONObject.fromObject(stu);        //2)使用JSONArray
        JSONArray array=JSONArray.fromObject(stu);
        String strJson=json.toString();
        String strArray=array.toString();
jsonlib将json字符串转化成对象,如下
//定义两种不同格式的字符串
        String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";        //1)使用JSONObject
        JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);        //2)使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(arrayStr);        //获得jsonArray的第一个元素
        Object o=jsonArray.get(0);
        JSONObject jsonObject2=JSONObject.fromObject(o);
        Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);        
        System.out.println("stu:"+stu);        
        System.out.println("stu2:"+stu2);
猜你喜欢: