JSON-libAPI是一个 Java 库,用于以 JSON 格式序列化和反序列化 java bean、映射、数组和集合。我们需要将 JSON 字符串转换为 bean,方法是先将字符串转换为 JSON 对象,然后将其转换为 java 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 ]
登录后复制
以上就是如何使用Java中的JSON-lib API将JSON字符串转换为Bean?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3041732.html