首页> Java> java教程> 正文

如何使用Java中的JSON-lib API将JSON对象转换为bean?

WBOY
发布: 2023-09-05 10:33:02
转载
1178 人浏览过

如何使用Java中的JSON-lib API将JSON对象转换为bean?

JSONObject类是一个包含名称/值对(无序)的集合,其中bean是一个具有其成员字段的settergetter方法的类。我们可以使用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 ]
登录后复制

以上是如何使用Java中的JSON-lib API将JSON对象转换为bean?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!