使用json-lib组件实现
* 需要
* json-lib-2.4-jdk15.jar
* ezmorph-1.0.6.jar
* commons-collections-3.1.jar
* commons-lang-2.0.jar
支持
UserInfos实体类
private String id;
private String name;
..get/set
LoginAccount实体类
private String id;
private String account;
private UserInfos userInfos;
..get/set
javaBean转换为Json
//创建LoginAccount对象的集合
List<LoginAccount> listJson=new ArrayList<LoginAccount>();
//制作数据
LoginAccount lAccount1=new LoginAccount();
lAccount1.setId("L001");
lAccount1.setAccount("xiaoMing");
UserInfos userInfos1=new UserInfos();
userInfos1.setId("001");
userInfos1.setName("小明");
lAccount1.setUserInfos(userInfos1);
LoginAccount lAccount2=new LoginAccount();
lAccount2.setId("L002");
lAccount2.setAccount("xiaoHong");
UserInfos userInfos2=new UserInfos();
userInfos2.setId("002");
userInfos2.setName("小红");
lAccount2.setUserInfos(userInfos2);
LoginAccount lAccount3=new LoginAccount();
lAccount3.setId("L003");
lAccount3.setAccount("xiaoHei");
UserInfos userInfos3=new UserInfos();
userInfos3.setId("003");
userInfos3.setName("小黑");
lAccount3.setUserInfos(userInfos3);
//添加数据
listJson.add(lAccount1);
listJson.add(lAccount2);
listJson.add(lAccount3);
//将List转换为JSON
JSONArray jsonArray=JSONArray.fromObject(listJson);
//输出JSON字符串
System.out.println(jsonArray.toString());
json转换为javaBean
//创建JSON字符串
String loginAccountJSON="[{id:\"L0001\",account:\"xiaoMing\",userInfos:{id:\"U0001\",name:\"小明\"}},{id:\"L0001\",account:\"xiaoHong\",userInfos:{id:\"U0002\",name:\"小红\"}},{id:\"L0001\",account:\"xiaoHei\",userInfos:{id:\"U0003\",name:\"小黑\"}}]";
//创建JSON对象
JSONArray jsonArrays = (JSONArray) JSONSerializer.toJSON(loginAccountJSON);
//设置list集合
List list=(List) JSONSerializer.toJava(jsonArrays);
//遍历
for(Object object:list){
JSONObject jsonObject = JSONObject.fromObject(object);
LoginAccount loginAccount = (LoginAccount) JSONObject.toBean(jsonObject,LoginAccount.class);
//输出获得的LoginAccount实体类的数据
System.out.println("id="+loginAccount.getId()+";account="+loginAccount.getAccount()+";userInfo.id="+loginAccount.getUserInfos().getId()+";userInfo.name="+loginAccount.getUserInfos().getName());
}