JSON---java对象转化

JSONOject.parseObject(String str,目标对象.class);//把json串转为对象

JSONOject.toJSONString(object);//把object转换为Json串。

http://www.cnblogs.com/free-dom/p/5801866.html

创建一个实体类Student

public class Student {
//姓名
private String name;
//年龄
private String age;
//住址
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", address="
+ address + "]";
}

}

下面写一个方法用来将student对象转换为json

public static void convertObject() {
        
        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();
        
        System.out.println("strJson:"+strJson);
        System.out.println("strArray:"+strArray);
    }

JSONObject与JSONArray方法打印结果如下:

strJson:{"address":"北京市西城区","age":"23","name":"JSON"}
strArray:[{"address":"北京市西城区","age":"23","name":"JSON"}]
JSONArray jsonArray=JSONArray.fromObject(arrstr);
//获得json数组的第一个元素
Object o = jsonArray.get(0);
JSONObject jsonObject = JSONObject.fromObject(o);
Student stu = (Student)JSONObject.toBean(jsonObject,Student.class);

 

posted @ 2017-09-06 07:51  大一脚步  阅读(155)  评论(0编辑  收藏  举报