javabean和json互相转换

      工作中经常遇到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 obj = (Content) JSON.parseObject(content, new TypeReference>(){});

使用java构建测试数据

	/**
	 * 造请求数据
	 * @return
	 */
	private static String createRequestData() {
		Content ct = new Content();
		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);
	}


你可能感兴趣的:(java)