n" ); map.put( "age", 25 ); map.put( "date", new Date() ); JSONObject jsonObject = JSONObject.fromObject( map ); System.out.println( jsonObject ); // prints {"name":"json","age":25,"date":"..."} }//自定义类型转换成 json,需要实现序列化接口或者注册 Morpher@Testpublic void testBeanToJSON(){MyBean myBean = new MyBean(); myBean.setName( "json" ); myBean.setAge( 25 ); myBean.setDate( new Date() ); JSONObject jsonObject = JSONObject.fromObject( myBean, new BeanMorpher() ); System.out.println( jsonObject ); // prints {"name":"json","age":25,"date":"..."} }/** * 自定义类型转换,如果属性是其他自定义类型,那么需要注册 Morpher * * @throws Exception */@Testpublic void testCustomBeanWithNestedBeanToJSON() throws Exception{MyBean myBean = new MyBean(); myBean.setName( "json" ); myBean.setAge( 25 ); myBean.setNestedBean( new NestedBean() ); //注册 Morpher,处理嵌套的自定义类型 MorpherRegistry registry = new MorpherRegistry(); registry.register( MyBean.class, new BeanMorpher() ); registry.register( NestedBean.class, new BeanMorpher() ); JSONUtils.configure( registry ); JSONObject jsonObject = JSONObject.fromObject( myBean, registry ); System.out.println( jsonObject ); // prints {"name":"json","age":25,"nestedBean":{...}} }}class MyBean{private String name; private int age; private Date date; private NestedBean nestedBean; //getters and setters...}class NestedBean{private String nestedProp; //getters and setters...}
剩余7页未读,继续阅读
- 粉丝: 1
- 资源: 74
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助