1. 程式人生 > >jsonarray和jsonobject封裝string

jsonarray和jsonobject封裝string

案例:一份問卷指派給多個學生,每個學生對該問卷進行答題,業務要求:一份問卷下有很多個問卷標題,每個標題選有很多個選項,則統計每個選項下有哪些學生選擇了,統計學生id和學生姓名。

問卷原型圖:

頁面統計原型圖:

準備工作:

eclipse4.564位   jdk1.7 64位 所需jar:fastjson-1.1.24.jar

測試程式碼:

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.JsonObject;
/**
 *@class:Test2 
 *@descript:業務要求:
 *1.通過問卷id查詢該問卷指派了所有學生完成的檔案
 *2.統計該問卷下每個選項有哪些學生選擇了顯示學生id和學生姓名,學生人數
 *@date:2016年11月9日 上午9:27:59
 *@author sanghaiqin
 *@version:V1.0
 */
public class Test2 {
	public static void main(String[] args) {
		
		//測試json資料
		String jsonStr1="["+
         "{"+
	        "\"identify\": \"家長\","+
	        "\"title\": \"家長問題1\","+
	        "\"type\": \"單選\","+
	        "\"options\": ["+
	            "{"+
	                "\"title\": \"A\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"B\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"C\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"D\","+
	                "\"isanswer\": true"+
	            "}"+
	        "]"+
	   "},"+
	    "{"+
	        "\"identify\": \"家長\","+
	        "\"title\": \"家長問題2\","+
	        "\"type\": \"多選\","+
	        "\"options\": ["+
	            "{"+
	                "\"title\": \"A\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"B\","+
	                "\"isanswer\": true"+
	            "},"+
	            "{"+
	                "\"title\": \"C\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"D\","+
	                "\"isanswer\": true"+
	            "}"+
	        "]"+
	    "},"+
	    "{"+
	        "\"identify\": \"教師\","+
	        "\"title\": \"教師問題1\","+
	        "\"type\": \"單選\","+
	        "\"options\": ["+
	            "{"+
	                "\"title\": \"A\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"B\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"C\","+
	                "\"isanswer\": false"+
	            "},"+
	            "{"+
	                "\"title\": \"D\","+
	                "\"isanswer\": false"+
	            "}"+
	        "]"+
	   " },"+
	    "{"+
	       "\"identify\": \"全部\","+
	       "\"title\": \"家長教師問題1\","+
	       "\"type\": \"單選+填空\","+
	        "\"options\": ["+
	           " {"+
	               "\"title\": \"A\","+
	               "\"isanswer\": true"+
	            "},"+
	           " {"+
	              " \"title\": \"B\","+
	               "\"isanswer\": false"+
	            "},"+
	           " {"+
	               "\"title\": \"C\","+
	               "\"isanswer\": false"+
	            "},"+
	           " {"+
	                "\"title\": \"D\","+
	                "\"isanswer\": false"+
	           " }"+
	        "]"+    
	     " }"+
	  "]";
        
        String jsonStr2="[{"+
    	        "\"identify\": \"家長\","+
    	        "\"title\": \"家長問題1\","+
    	        "\"type\": \"單選\","+
    	        "\"options\": ["+
    	            "{"+
    	                "\"title\": \"A\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"B\","+
    	                "\"isanswer\": true"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"C\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"D\","+
    	                "\"isanswer\": false"+
    	            "}"+
    	        "]"+
    	    "},"+
    	    "{"+
    	        "\"identify\": \"家長\","+
    	        "\"title\": \"家長問題2\","+
    	        "\"type\": \"多選\","+
    	        "\"options\": ["+
    	            "{"+
    	                "\"title\": \"A\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"B\","+
    	                "\"isanswer\": true"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"C\","+
    	                "\"isanswer\": true"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"D\","+
    	                "\"isanswer\": false"+
    	            "}"+
    	        "]"+
    	    "},"+
    	    "{"+
    	        "\"identify\": \"教師\","+
    	        "\"title\": \"教師問題1\","+
    	        "\"type\": \"單選\","+
    	        "\"options\": ["+
    	            "{"+
    	                "\"title\": \"A\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"B\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"C\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"D\","+
    	                "\"isanswer\": false"+
    	            "}"+
    	        "]"+
    	    "},"+
    	    "{"+
    	        "\"identify\": \"全部\","+
    	        "\"title\": \"家長教師問題1\","+
    	        "\"type\": \"單選+填空\","+
    	        "\"options\": ["+
    	            "{"+
    	                "\"title\": \"A\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"B\","+
    	                "\"isanswer\": true"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"C\","+
    	                "\"isanswer\": false"+
    	            "},"+
    	            "{"+
    	                "\"title\": \"D\","+
    	                "\"isanswer\": false"+
    	            "}"+
    	        "]"+
    	    "}"+
    	"]";
        
        //封裝測試list集合資料
        List<Map<String,Object>> dataList=new ArrayList<Map<String,Object>>();
		Map<String,Object> dataMap1=new HashMap<String,Object>();
		Map<String,Object> dataMap2=new HashMap<String,Object>();
		dataMap1.put("studentid", 66);
		dataMap1.put("studentname", "李珺雯");
		dataMap1.put("studentanswer", jsonStr1);
		dataMap2.put("studentid", 158);
		dataMap2.put("studentname", "瞿樂萱");
		dataMap2.put("studentanswer", jsonStr2);
		dataList.add(dataMap1);
		dataList.add(dataMap2);
		
		//迴圈list集合資料
		for(Map<String, Object> data:dataList){
			String studentId=data.get("studentid").toString();
//			System.out.println("studentId:"+studentId);
		}
		
		//封裝所有滿足條件資料
		Map<String, Map<String, Map<String, List<StudentVo>>>> result=new HashMap<String, Map<String,Map<String,List<StudentVo>>>>();
		//迴圈集合資料
		for(Map<String, Object> dataMap:dataList){
			//學生id
			Long studentid=Long.parseLong(dataMap.get("studentid").toString());
			//學生姓名
			String studentname=dataMap.get("studentname").toString();
			//學生回答
			JSONArray answerArray=JSONArray.parseArray(dataMap.get("studentanswer").toString());
			//迴圈學生回答json陣列
			for(int i=0;i<answerArray.size();i++){
				//問卷定義如:"家長","教師","全部"
				String identify=JSONObject.parseObject((JSONObject.toJSONString(answerArray.get(i)))).getString("identify");
				//問卷型別如:"單選","多選","單選+填空"
				String types=JSONObject.parseObject((JSONObject.toJSONString(answerArray.get(i)))).getString("type");
				//只統計問卷定義不等於教師且問卷型別為單選或者多選
				if(!"教師".equals(identify) && ("單選".equals(types) || "多選".equals(types))){
					//問卷標題如:"家長問題1","家長問題2"
					String titles=JSONObject.parseObject((JSONObject.toJSONString(answerArray.get(i)))).getString("title");
					//問卷選項如:"A","B","C","D"
					String options=JSONObject.parseObject(JSONObject.toJSONString(answerArray.get(i))).getString("options");
					//將問卷選項轉換為json陣列
					JSONArray optionsArray=JSONArray.parseArray(options);
					//迴圈問卷選項
					for(int j=0;j<optionsArray.size();j++){
						 //問卷選項名稱
						 String title=JSONObject.parseObject(JSONObject.toJSONString(optionsArray.get(j))).getString("title"); 
						 //是否答題
						 boolean isanswer=JSONObject.parseObject(JSONObject.toJSONString(optionsArray.get(j))).getBoolean("isanswer");
						 //判斷學生是否選中了答題,選中了則統計學生id和姓名,否則只統計每個選項標題名稱
						 if(isanswer){
							 //若答題了則新增學習資訊
                             StudentVo studentVo = new StudentVo();
                             studentVo.setStudentName(studentname);
                             studentVo.setStudentId(studentid);
                             countStudents(isanswer,titles,title,studentVo,result);
						 }else{//未選中答題
							//沒有答題不需要新增學生資訊
							 countStudents(isanswer,titles,title,null,result);
						 }
					}
				}// end if
			}// end answerarray
		}// end datalist
		
		String resultStr=JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
//		System.out.println("resultStr:"+resultStr);
		
		//封裝返回資料
		JSONArray dataArray=new JSONArray();
		JSONObject total=new JSONObject();
		total.put("total", dataList.size());
		dataArray.add(total);
		//迴圈得到的資料
		for(Map.Entry<String, Map<String, Map<String,List<StudentVo>>>> titlesEntry:result.entrySet()){
			//封裝返回資料
			JSONObject dataObj=new JSONObject();
			//得到問卷標題如:"家長問題1","家長問題2"
		    String titles=titlesEntry.getKey();
		    //封裝問卷選項資料
		    JSONArray optionsArray=new JSONArray();
		    //得到問卷選項名稱
		    Map<String, Map<String,List<StudentVo>>> titlesValue = titlesEntry.getValue();
		    for(Map.Entry<String, Map<String,List<StudentVo>>> titleEntry:titlesValue.entrySet()){
		    	//封裝問卷選項資料
		    	JSONObject optionsObj=new JSONObject();
		    	//問卷選項名稱
		    	String title=titleEntry.getKey();
		    	//得到學生資訊
		    	Map<String,List<StudentVo>> titleValue = titleEntry.getValue();
		    	//封裝學生資訊
		    	JSONArray studentsArray=new JSONArray();
		    	for(Map.Entry<String,List<StudentVo>> students :titleValue.entrySet()){
		    		//得到所有學生資訊
		    		List<StudentVo> vos=students.getValue();
		    		if(vos!=null && !vos.isEmpty()){//有資料
		    			for(StudentVo vo:vos){
		    				Long studentId=vo.getStudentId();
		    				String studentName=vo.getStudentName();
		    				JSONObject studentObj=new JSONObject();
		    				studentObj.put("studentId", studentId);
		    				studentObj.put("studentName", studentName);
		    				studentsArray.add(studentObj);
		    			}
		    			//統計學生人數
		    			optionsObj.put("num", studentsArray.size());
		    		}else{//無資料
		    			//統計學生人數
		    			optionsObj.put("num", 0);
		    		}
		    	}
		    	//封裝問卷選項
		    	optionsObj.put("title", title);
		    	optionsObj.put("students", studentsArray);
		    	optionsArray.add(optionsObj);
		    }
		    //封裝問卷標題
		    dataObj.put("title", titles);
		    dataObj.put("options", optionsArray);
		    dataArray.add(dataObj);
	  }
	
	  System.out.println("dataArray:"+dataArray.toString());
		
	
		
	}
	
	/**
	 * @descript:抽取公共方法,判斷學生是否答題,若答題則新增學生資訊,否則不新增,只統計選項標題名稱
	 * @param isanswer 學生是否答題
	 * @param titles 問卷標題
	 * @param title  問卷選項標題名稱
	 * @param result 封裝滿足條件結果集
	 */
	protected static void countStudents(Boolean isanswer,String titles,String title, StudentVo studentVo,Map<String, Map<String, Map<String, List<StudentVo>>>> result){
		//判斷結果集是否已經包含問卷標題
		if(result.containsKey(titles)){
			//通過問卷標題得到問卷選項名稱
			Map<String, Map<String, List<StudentVo>>> titleMap=result.get(titles);
			if(titleMap!=null && !titleMap.isEmpty()){
				//通過問卷選項名稱得到學生資訊
				Map<String, List<StudentVo>> studentsMap=titleMap.get(title);
				if(studentsMap!=null && !studentsMap.isEmpty()){
					//得到學生資訊
					List<StudentVo> studentVos=studentsMap.get("students");
					//判斷學生是否答題,若答題則新增學生資訊,否則不新增
					if(isanswer){
						studentVos.add(studentVo);
					}
					//學生資訊
					studentsMap.put("students", studentVos);
					//問卷選項名稱
					titleMap.put(title, studentsMap);
				}else{//學生資訊為空則建立
					studentsMap=new HashMap<String, List<StudentVo>>();
					//建立學生資訊集合
					List<StudentVo> studentVos=new ArrayList<StudentVo>();
					if(isanswer){
						studentVos.add(studentVo);
					}
					//學生資訊
					studentsMap.put("students", studentVos);
					//問卷選項名稱
					titleMap.put(title, studentsMap);
				}
			}else{//問卷選項名稱為空則建立
				titleMap= new HashMap<String, Map<String, List<StudentVo>>>();
				Map<String, List<StudentVo>> studentsMap=new HashMap<String, List<StudentVo>>();
				List<StudentVo> studentVos=new ArrayList<StudentVo>();
				if(isanswer){
					studentVos.add(studentVo);
				}
				//學生資訊
				studentsMap.put("students", studentVos);
				//問卷選項名稱
				titleMap.put(title, studentsMap);
			}
		}else{//問卷標題不存在則建立
			Map<String, Map<String, List<StudentVo>>> titleMap= new HashMap<String, Map<String, List<StudentVo>>>();
			Map<String, List<StudentVo>> studentsMap=new HashMap<String, List<StudentVo>>();
			List<StudentVo> studentVos=new ArrayList<StudentVo>();
			if(isanswer){
				studentVos.add(studentVo);
			}
			//學生資訊
			studentsMap.put("students", studentVos);
			//問卷選項名稱
			titleMap.put(title, studentsMap);
			//問卷標題
			result.put(titles, titleMap);
		}
	}
	
	
	
}

上述測試程式碼中對測試資料進行抽取滿足條件的資料resultStr效果:

{
    "家長問題1": {
        "A": {
            "students": []
        },
        "B": {
            "students": [
                {
                    "studentId": 158,
                    "studentName": "瞿樂萱"
                }
            ]
        },
        "C": {
            "students": []
        },
        "D": {
            "students": [
                {
                    "studentId": 66,
                    "studentName": "李珺雯"
                }
            ]
        }
    },
    "家長問題2": {
        "A": {
            "students": []
        },
        "B": {
            "students": [
                {
                    "studentId": 66,
                    "studentName": "李珺雯"
                },
                {
                    "studentId": 158,
                    "studentName": "瞿樂萱"
                }
            ]
        },
        "C": {
            "students": [
                {
                    "studentId": 158,
                    "studentName": "瞿樂萱"
                }
            ]
        },
        "D": {
            "students": [
                {
                    "studentId": 66,
                    "studentName": "李珺雯"
                }
            ]
        }
    }
}
對輸出滿足條件的資料進行重新封裝轉換為json資料dataArray效果:
[
    {
        "total": 2
    },
    {
        "options": [
            {
                "num": 1,
                "students": [
                    {
                        "studentId": 66,
                        "studentName": "李珺雯"
                    }
                ],
                "title": "D"
            },
            {
                "num": 0,
                "students": [],
                "title": "A"
            },
            {
                "num": 2,
                "students": [
                    {
                        "studentId": 66,
                        "studentName": "李珺雯"
                    },
                    {
                        "studentId": 158,
                        "studentName": "瞿樂萱"
                    }
                ],
                "title": "B"
            },
            {
                "num": 1,
                "students": [
                    {
                        "studentId": 158,
                        "studentName": "瞿樂萱"
                    }
                ],
                "title": "C"
            }
        ],
        "title": "家長問題2"
    },
    {
        "options": [
            {
                "num": 1,
                "students": [
                    {
                        "studentId": 66,
                        "studentName": "李珺雯"
                    }
                ],
                "title": "D"
            },
            {
                "num": 0,
                "students": [],
                "title": "A"
            },
            {
                "num": 1,
                "students": [
                    {
                        "studentId": 158,
                        "studentName": "瞿樂萱"
                    }
                ],
                "title": "B"
            },
            {
                "num": 0,
                "students": [],
                "title": "C"
            }
        ],
        "title": "家長問題1"
    }
]


相關推薦

jsonarrayjsonobject封裝string

案例:一份問卷指派給多個學生,每個學生對該問卷進行答題,業務要求:一份問卷下有很多個問卷標題,每個標題選有很多個選項,則統計每個選項下有哪些學生選擇了,統計學生id和學生姓名。 問卷原型圖: 頁面統計原型圖: 準備工作: eclipse4.564位   jdk1.7 6

JsonArrayJsonObject的使用

getjson ati array對象 stat println 總結 內容 lean == import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonTest {

JSONArrayJSONObject

alt 大括號 image arr vpd ray json fff col 1, JSONObjectjson對象,就是一個鍵對應一個值,使用的是大括號{},即:{key:value}2,JSONArrayjson數組,是用中括號[],數組裏面的項也是json鍵值對格式J

遍歷jsonArrayjsonObject

ring gpo key log pri while sys rom ons 遍歷jsonArray String str = "[{name:‘a‘,value:‘aa‘},{name:‘b‘,value:‘bb‘},{name:‘c‘,value:‘cc‘}]" ;

Android開發將List轉化為JsonArrayJsonObject

客戶端需要將List<Object>轉化為JsonArray和JsonObject的方法: 首先,List中的Object的屬性需要是public: class Person { public String name; public S

fastjson的JSONArrayJSONObject

什麼是JSON? JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。 易於人閱讀和編寫。同時也易於機器解析和生成。 它基於javascript Programming Language, Standard

後臺遍歷json資料:JsonArrayJsonObject遍歷方法

一:遍歷JsonArray // 一個未轉化的字串 String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ;

Java (JSONArrayJSONObjectString字串中)引號""替換成"-"

String value=(a.toString()).replace("\"\"", "\"-\""); 解釋: 原來,jsonObject傳過去有很多空值。 JSONArray a = new JSONArray(); jsonObject.accumulate("da

JSON學習(四):JsonArrayJsonObject遍歷方法

一:遍歷JsonArray // 一個未轉化的字串 String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:

JAVA中使用JSONArrayJSONObject

port ack i++ 大括號 ttpClient 一對一 pri 對象 arr json 就是一個鍵對應一個值,簡單的一對一關系。 JSONObject json對象,就是一個鍵對應一個值(鍵值對),使用的是大括號{ },如:{key:value} JSONA

list去重、list統計,以及(StringJSONObjectString轉list、List轉List、JSONArray)之間的轉換

package com.wendao.controller;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;imp

JAVAEE——SSH項目實戰02:客戶列表BaseDao封裝

nbsp jstl n) top 默認 ica ring put ava 作者: kent鵬 轉載請註明出處: http://www.cnblogs.com/xieyupeng/p/7129152.html 該項目在SSH三大框架整合基礎上進行開發:http://www

jsonxml封裝數據、數據緩存到文件中

用戶 lena 數據緩存 完全 數據類型 lin print 函數 response 一、APP的通信格式之xml xml:擴展標記語言,可以用來標記數據,定義數據類型,是一種允許用戶對自己標記語言進行定義的源語言。XML格式統一,擴平臺語言,非常適合數據傳輸和通信,業界

封裝封裝類比較相同不intInteger

com margin idt val image 相同 -1 img wid A.所有和int(非封裝類比較的,只要數值相同就行) B.io3由valueof弄出來的,所以和io1相同 C.io4是new出來的,所以地址不一樣,就不相同 D.和A相同封裝類和非封裝類比較相

okhttp第三方封裝好的OKHttp庫-okhttp-utils

projects https esp lang call 實例化 透明 square sample 1_OKHttp簡介 1.1_簡介 OKHttp是一款高效的HTTP客戶端,支持連接同一地址的鏈接共享同一個socket,通過連接池來減小響應延遲,還有透明的GZIP壓縮,請

Java下StringList<String>的互相轉換

pan int blank 參考 net onu array pos body // List轉換為String數組 List<String> list = new ArrayList<String>(); list.add("a1"

Qt與FFmpeg聯合開發指南(四)——編碼(2):完善功能基礎封裝

v_op buffer 目前 front from 幀率 inter 博客 int 上一章我用一個demo函數演示了基於Qt的音視頻采集到編碼的完整流程,最後經過測試我們也發現了代碼中存在的問題。本章我們就先處理幾個遺留問題,再對代碼進行完善,最後把編碼功能做基礎封裝。 一

intInteger,StringString(包裝類)

內存空間 mage image out info clas 技術 ima spa 1.int和Integer的值如果是一樣的,則是在內存中開辟相同的內存空間 2.但是String和String(包裝類)是不一樣的 代碼演示: int a=1;

C++之MutexLockMutexLockGuard封裝

執行 div unistd.h sta lock ptr cas turn sleep thread.h #ifndef __WD_MUTEXLOCK_H__ #define __WD_MUTEXLOCK_H__ #include <pthread.h>

ssh執行遠程命令bash -c string的用法

sign -m sla mysql conf follow exit ash hub ssh執行遠程命令和bash -c string的用法說明:今天在學習k8s的Run a Replicated Stateful Application (運行一個有狀態應用的副本)時,官