博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JSONObject的toBean 和 fromObject
阅读量:5057 次
发布时间:2019-06-12

本文共 2349 字,大约阅读时间需要 7 分钟。

public static void main(String[] args) {Map map=new HashMap();map.put("我","妹");map.put("擦","哇");map.put("你","呀");JSONObject json = JSONObject.fromObject(map);System.out.println(json);}輸出的結果 {
"我":"妹","擦":"哇","你":"呀"} toBean();首先一个javabean对象public class Student {private int id ;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String toString(){return this.id + ", " + this.name + ", " + this.age;}}然后测试toBean方法的类import net.sf.json.JSONObject;public class ToBeanTest {public static void main(String[] args) {String json = "{id:'1001',name:'张三',age:'22'}";Student stu = new Student();JSONObject obj = JSONObject.fromObject(json);stu = (Student)JSONObject.toBean(obj, Student.class);System.out.println(stu);}}输出结果为1001, 张三, 22 然后我们在修改修改import net.sf.json.JSONObject;public class ToBeanTest {public static void main(String[] args) {String json = "{id:'1001',name:'张三'}";Student stu = new Student();JSONObject obj = JSONObject.fromObject(json);stu = (Student)JSONObject.toBean(obj, Student.class);System.out.println(stu);}}把年龄给去掉age为int型,输出结果为:1001, 张三, 0 然后再做小小改动import net.sf.json.JSONObject;public class ToBeanTest {public static void main(String[] args) {String json = "{id:'1001',age:'22'}"; Student stu = new Student();JSONObject obj = JSONObject.fromObject(json);stu = (Student)JSONObject.toBean(obj, Student.class);System.out.println(stu);}}把姓名给去掉name为String型,输出结果为:1001, null, 22 再改动一下:import net.sf.json.JSONObject;public class ToBeanTest {public static void main(String[] args) {String json = "{id:'1001',name:'张三',age:'nn'}";Student stu = new Student();JSONObject obj = JSONObject.fromObject(json);stu = (Student)JSONObject.toBean(obj, Student.class);System.out.println(stu);}}把age改成非整形,输出结果为:1001, 张三, 0 再改动一下:import net.sf.json.JSONObject;public class ToBeanTest {public static void main(String[] args) {String json = "{id:'1001',name:'张三',age:'22',sex:'男'}";Student stu = new Student();JSONObject obj = JSONObject.fromObject(json);stu = (Student)JSONObject.toBean(obj, Student.class);System.out.println(stu);}}加了一个sex:'男'的一对键值,输出结果为:1001, 张三, 22

 

转载于:https://www.cnblogs.com/chenyanlong/p/7374572.html

你可能感兴趣的文章
Linux 的cp命令
查看>>
SQL语句
查看>>
ThinkPHP里面用原生SQL
查看>>
博客园批量发闪存,获取小星星
查看>>
【EXCEL】冻结窗口的设置
查看>>
Hey~
查看>>
2576
查看>>
2719
查看>>
css中一些常用技巧
查看>>
oracle cast (一)
查看>>
第20章—跨域访问(CORS)
查看>>
关于C#的DataGridView设置了DataSource后Rows无值问题
查看>>
是否需要有代码规范
查看>>
php中点击网页不跳转执行程序
查看>>
Centos-6.5 + python3 + mysql5.6 环境搭建
查看>>
主要解决了Gridview导出到Excel
查看>>
05_zookeeper的ACL
查看>>
[Android实例] 天天动听 悬浮歌词(迷你歌词)效果解读
查看>>
在sql语法里面定义变量
查看>>
centOS 6设置开机自启
查看>>