JSON是基于{“键”:“值”} 对的存在,当然我们也可以多层嵌套,对于刚刚学习JSON十分便捷而且很好用,很容理解。话不多说直接上代码:
public String queryPostInterface(String theNewInterface) throws Exception {
JSONObject jsonObject = new JSONObject(theNewInterface);
String postId = AESUtil.Decrypt(jsonObject.getString("post_id"), cKey);//帖子ID
StringBuffer sb = new StringBuffer();
int size = 0;//定义一个变量用来接收循环多少次(共多少条数据)
if(theNewInterface!=null && !"".equals(theNewInterface)){
if (postId != null && !"".equals(postId)) {
//获取帖子信息 tieba(具体业务自己查询这里只是个例子)
TyPostInfo postInfo = tyPostBarService.selpostInfoById(Long.valueOf(postId));
//查询帖子回复信息(具体业务自己查询这里只是个例子)(泛型是个对象)
List replies = tyPostBarService.selectHuiHuid(Long.valueOf(postId));
if (replies != null) {
sb.append("{\"stateCode\": " + 1 + ","); //JSON串的开头信息
sb.append(" \"message\": \"成功\",");
sb.append("\"replayList\": [");//JSON结果集
for (TyPostbarReply reply : replies) { //循环结果集,进行拼接
//获取用户ID uuid
Long userId = iUserInfoService.getIdByUserUUID(reply.getReplyUserid().toString()); //select UO.updateUserId from USER_INFO UO where id=?
UserInfoVo usesr = tyPostBarService.selectById_yb(userId);
String photo = "";
if (usesr.getUserPhoto() != null) {
photo = usesr.getUserPhoto().substring(0, usesr.getUserPhoto().lastIndexOf("."));
} else {
photo = "";
}
sb.append("{\"userPhoto\": \"" + photo.toString() + "\",");//用户照片
sb.append("\"userName\": \"" + usesr.getRealName().toString() + "\",");//用户姓名
sb.append("\"floor\": \"" + reply.getFloorNum().toString() + "\",");//楼层数
sb.append("\"barID\": \"" + postInfo.getPostBarId().toString() + "\",");//贴吧Id
sb.append("\"postID\": \"" + postInfo.getId().toString() + "\",");//帖子id
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sb.append("\"createTime\": \"" + sdf.format(reply.getCreateTime()) + "\",");//创建时间
sb.append("\"content\": \"" + reply.getReplyContent().toString() + "\"");//评论内容
size = size + 1;//循环一次+1
if (size < replies.size()) {//这里需要注意下。如果循环总条数小于查出来的总条数每次循环完毕一次都在 “},” 加上“,” 否则不加 “ ,”
sb.append("},");
} else {
sb.append("}");
}
}
sb.append("]}"); //最后在拼接最外层(在循环外部)
}
} else {
sb.append("{\"stateCode\":" + 0 + ",");
sb.append("\"message\":\" 传入参数为空\"}");
}
}else{
sb.append("{\"stateCode\":" + 0 + ",");
sb.append