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));
//查詢帖子回復信息(具體業務自己查詢這里只是個例子)(<TyPostbarReply>泛型是個對象)
List<TyPostbarReply> 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("\"message\":\" 傳入參數為空\"}");
}
return AESUtil.Encrypt(sb.toString(), cKey);
}
}
最后就會拼接成JSON串,具體業務具體分析,這只是一個方發,一個思想,編程重在思想!!!
解析和JSON基本用法:https://www.cnblogs.com/ysySelf/p/10985410.html
以上是最基本的拼接方式下面看下json用法:
1:創建JSONObject,添加屬性
//創建JSONObject
JSONObject json = new JSONObject();
//添加屬性
json.put("username", "張三");
json.put("password", "123");
//打印
System.out.println(json);
//增加屬性
json.element("sex", "男");
json.put("age", 18);
System.out.println(json);
根據key返回輸出 :System.out.println(json.get("sex"));
2:判斷輸出對象的類型
boolean isArray = json.isArray(); //是否是數組
boolean isEmpty = json.isEmpty(); // 是否為空
boolean isNullObject = json.isNullObject(); // 是否為空對象
System.out.println("是否數組:"+isArray+", 是否空:"+isEmpty+", 是否空為空對象:"+isNullObject);
3:把JSONArray添加到JSONObject中
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "張三");
jsonArray.add(1, "123");
//開始添加
json.element("student", jsonArray);
System.out.println(json);
詳細代碼如下:
//創建JSONObject
JSONObject json = new JSONObject();
//添加屬性
json.put("username", "張三");
json.put("password", "123");
//打印
System.out.println(json);
//增加屬性
json.element("sex", "男");
json.put("age", 18);
System.out.println(json);
//根據key返回
System.out.println(json.get("sex"));
//判斷輸出對象的類型
boolean isArray = json.isArray();
boolean isEmpty = json.isEmpty();
boolean isNullObject = json.isNullObject();
System.out.println("是否數組:"+isArray+", 是否空:"+isEmpty+", 是否空為空對象:"+isNullObject);
System.out.println("=====");
//把JSONArray添加到JSONObject中
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "張三");
jsonArray.add(1, "123");
//開始添加
json.element("student", jsonArray);
System.out.println(json);
JSONArray:
public static void main(String[] args) {
//創建JSONArray
JSONArray jsonArray = new JSONArray();
//添加
jsonArray.add(0, "張三");
jsonArray.add(1, "123");
jsonArray.element("男");
System.out.println(jsonArray);
//根據下標返回輸出
System.out.println(jsonArray.get(0));
//根據下標設置新值,修改
jsonArray.set(0, "李四");
System.out.println(jsonArray);
//把JSONObject放入到JSONArray中
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "張三");
jsonObject.put("password", "123");
jsonArray.add(jsonObject);
System.out.println(jsonArray);
//循環輸出
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}
}
JavaBean與json字符串互轉
public class Student{
private String username;
private String password;
//get set
}
定義對象,JavaBean(對象)對象轉json字符串
//定義對象
Student stu = new Student("張三", "123456");
//JavaBean對象轉json字符串
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
json字符串轉為javaBean 關鍵字 toBean();
//json字符串轉為javaBean
//定義json字符串
String jsondata = "{\"username\":\"李四\", \"password\":\"123\"}";
//轉為json對象
JSONObject json = JSONObject.fromObject(jsondata);
//轉為JavaBean對象
Student stu2 = (Student)JSONObject.toBean(json, Student.class);
System.out.println(stu2.toString());
詳細代碼:
public static void main(String[] args) {
//定義對象
Student stu = new Student("張三", "123456");
//JavaBean對象轉json字符串
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
//json字符串轉為javaBean
//定義json字符串
String jsondata = "{\"username\":\"李四\", \"password\":\"123\"}";
//轉為json對象
JSONObject json = JSONObject.fromObject(jsondata);
//轉為JavaBean對象
Student stu2 = (Student)JSONObject.toBean(json, Student.class);
System.out.println(stu2.toString());
}
List與json字符串互轉:
先定義list集合,list轉json字符串
//定義list集合
List list = new ArrayList();
list.add(new Student("張三", "123"));
list.add(new Student("李四", "456"));
//list轉json字符串
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
json字符串轉list
//json字符串轉list
List list2 = new ArrayList();
String jsondata = "[{\"password\":\"123\",\"username\":\"張三\"},{\"password\":\"456\",\"username\":\"李四\"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for(int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i); //獲取到每一條. 0:[{\"password\":\"123\",\"username\":\"張三\"} ,1:{\"password\":\"456\",\"username\":\"李四\"}
Student stu2 = (Student)JSONObject.toBean(jsonObject2, Student.class);
list2.add(stu2);wozuile
}
System.out.println(list2);
全部代碼:
public static void main(String[] args) {
//定義list集合
List list = new ArrayList();
list.add(new Student("張三", "123"));
list.add(new Student("李四", "456"));
//list轉json字符串
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
//json字符串轉list
List list2 = new ArrayList();
String jsondata = "[{\"password\":\"123\",\"username\":\"張三\"},{\"password\":\"456\",\"username\":\"李四\"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for(int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
Student stu2 = (Student)JSONObject.toBean(jsonObject2, Student.class);
list2.add(stu2);
}
System.out.println(list2);
}
Map與json字符串互轉:
//定義map集合
Map map = new HashMap();
map.put("1", new Student("張三", "123"));
map.put("2", new Student("李四", "456"));
//Map轉json字符串
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
定義字符串map集合,map集合字符串轉為map:
//定義字符串map集合
String jsondata = "{\"1\":{\"password\":\"123\",\"username\":\"張三\"},\"2\":{\"password\":\"456\",\"username\":\"李四\"}}";
//map集合字符串轉為map
Map map2 = (Map)JSONObject.fromObject(jsondata); //強轉Map
Set set = map2.keySet(); // 獲取到所有得 key : 1 ,2
//打印 set 結果是:[1,2]
//定義迭代器,迭代輸出
Iterator ite = set.iterator();
while(ite.hasNext()) { // 這里需要注意再循環中操作數據在插入到幾何中一定要用迭代器
//取出一個字符串對象
String key = (String)ite.next(); // 1 ,2
//轉為json格式
JSONObject jsonObject = JSONObject.fromObject(map2.get(key)); // 通過每一個Key 動態獲取到對應的VALUE轉換成JSON
//轉為對象
Student stu = (Student)JSONObject.toBean(jsonObject, Student.class); //
System.out.println(key+" "+stu);
}
詳細代碼:
public static void main(String[] args) {
//定義map集合
Map map = new HashMap();
map.put("1", new Student("張三", "123"));
map.put("2", new Student("李四", "456"));
//Map轉json字符串
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
//定義字符串map集合
String jsondata = "{\"1\":{\"password\":\"123\",\"username\":\"張三\"},\"2\":{\"password\":\"456\",\"username\":\"李四\"}}";
//map集合字符串轉為map
Map map2 = (Map)JSONObject.fromObject(jsondata);
Set set = map2.keySet();
//定義迭代器,迭代輸出
Iterator ite = set.iterator();
while(ite.hasNext()) {
//取出一個字符串對象
String key = (String)ite.next();
//轉為json格式
JSONObject jsonObject = JSONObject.fromObject(map2.get(key));
//轉為對象
Student stu = (Student)JSONObject.toBean(jsonObject, Student.class);
System.out.println(key+" "+stu);
}
}
JSONArray與List互轉:
定義list集合,List轉型JSONArray
//定義list集合
List<Student> list = new ArrayList<Student>();
list.add(new Student("張三", "123"));
list.add(new Student("李四", "456"));
//List轉型JSONArray
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
JSONArray轉型List,JSONArray是用的上面的那個jsonArray變量
//JSONArray轉型List
List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());
Iterator<Student> ite = list2.iterator();
while(ite.hasNext()) {
Student stu = ite.next();
System.out.println(stu);
}
詳細代碼:
public static void main(String[] args) {
//定義list集合
List<Student> list = new ArrayList<Student>();
list.add(new Student("張三", "123"));
list.add(new Student("李四", "456"));
//List轉型JSONArray
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
//JSONArray轉型List
List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());
Iterator<Student> ite = list2.iterator();
while(ite.hasNext()) {
Student stu = ite.next();
System.out.println(stu);
}
}
運行結果:

JSONArray與數組互轉:
定義數組,數組轉JSONArray
//定義數組
boolean[] boolArray = {true, false, true};
//java數組轉JSONArray
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray.toString());
JSONArray轉java數組:
//JSONArray轉java數組
Object obj[] = jsonArray.toArray();
for(Object o : obj) {
System.out.print(o+"\t");
}
詳細代碼:
public static void main(String[] args) {
//定義數組
boolean[] boolArray = {true, false, true};
//java數組轉JSONArray
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray.toString());
//JSONArray轉java數組
Object obj[] = jsonArray.toArray();
for(Object o : obj) {
System.out.print(o+"\t");
}
}
運行結果:

以上是小弟自己總結出來的有不足的地方歡迎吐槽!學如逆水行舟不進則退!!!與君共勉!
