如何使用 Java 中的 JSON-lib API 将 JSON 字符串转换为 bean?
javajsonobject oriented programmingprogramming
JSON-lib API 是一个 Java 库,用于以 JSON 格式序列化和反序列化 java beans、map、数组 和 集合 。我们需要先将字符串转换为 JSON 对象,然后再将其转换为 Java bean,从而将 JSON 字符串转换为 bean。
语法
public static Object toBean(JSONObject jsonObject, Class beanClass)
在下面的程序中,我们可以将 JSON 字符串转换为 bean。
示例
import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; public class ConvertJSONStringToBeanTest { public static void main(String[] args) { String jsonStr = "{\"firstName\": \"Adithya\", \"lastName\": \"Sai\", \"age\": 30, \"technology\": \"Java\"}"; JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON System.out.println(jsonObj); Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean System.out.println(student.toString()); } public static class Student { private String firstName; private String lastName; private int age; private String technology; public Student() { } 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 getTechnology () { return technology; } public void setTechnology(String technology) { this.technology = technology; } public String toString() { return "Student[ " + "firstName = " + firstName + ", lastName = " + lastName + ", age = " + age + ", technology = " + technology + " ]"; } } }
输出
{"firstName":"Adithya","lastName":"Sai","age":30,"technology":"Java"} Student[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]