javabean和json互相转换
来源:互联网 发布:骑在银龙背上 知乎 编辑:程序博客网 时间:2024/05/18 13:25
工作中经常遇到javabean和json互相转换的场景。现就拿fastjson做为例子记录一下:
json:{"body":{"password":"password","username":"dahetao"},"head":{"appId":"id","transId":"123456"}}
json结构转换为javabean
推荐使用在线工具http://www.bejson.com/java2pojo/
直接转换为javabean下载即可。
String强转为javabean
Content<UserInfo> obj = (Content<UserInfo>) JSON.parseObject(content, new TypeReference<Content<UserInfo>>(){});
使用java构建测试数据
/** * 造请求数据 * @return */private static String createRequestData() {Content<UserInfo> ct = new Content<UserInfo>();Head head = new Head();head.setAppId("id");head.setTransId("123456");ct.setHead(head);UserInfo userInfo = new UserInfo();userInfo.setUsername("username");userInfo.setPassword("pwd");ct.setBody(userInfo);return JSONObject.toJSONString(ct);}
阅读全文