如何使用Java中的JSON-lib API将JSON对象转换为bean?
JSONObject 类是集合的名称/值对(无序),其中豆 是一类设置器 和Getter 的方法为其成员字段。我们可以使用JSONObject 类的toBean()方法将JSON对象转换为bean。
语法
public static Object toBean(JSONObject jsonObject, Class beanClass)
示例
import net.sf.json.JSONObject;
public class ConvertJSONObjToBeanTest {
public static void main(String[] args) {
mployee emp = new Employee("Sai", "Ram", 30, "Bangalore");
JSONObject jsonObj = JSONObject.fromObject(emp);
System.out.println(jsonObj.toString(3)); // pretty print JSON
emp = (Employee)JSONObject.toBean(jsonObj, Employee.class);
System.out.println(emp.toString());
} // Employee class
public static class Employee {
private String firstName, lastName, address;
private int age;
public Employee() {
}
public Employee(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Employee[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +
" ]";
}
}
}输出结果
{
"firstName": "Sai",
"lastName": "Ram",
"address": "Bangalore",
"age": 30
}
Employee[ firstName = Sai, lastName = Ram, age = 30, address = Bangalore ]热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练