實例自己想的一個實例應用場景:一個人可以有多個角色,例如:在家中是兒子,在學校是學生,在公司是程序員,一個人還可以辦好多業務
* 每個業務好多個人都可以辦,則標記(mark)就是記錄這唯一標識的(如id)業務和稱職
1.人實體類(People)
package com.hsinfo.web.Demo; import java.util.Set; /** * @Description:人的實體類 * @date 2018年7月22日,下午8:58:03 */ public class People { //說明信息 private String message; //每個人所扮演角色的唯一標記 private Set<String> markSet; public Set<String> getMarkSet() { return markSet; } public void setMarkSet(Set<String> markSet) { this.markSet = markSet; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.角色實體類(Role)
package com.hsinfo.web.Demo; /** * @Description:角色實體類 * @date 2018年7月22日,下午8:57:37 */ public class Role { private String mark; private String name; private int age; private String sex; public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
3.service業務邏輯處理接口
package com.hsinfo.web.Demo; import net.sf.json.JSONObject; public interface JsonDemoService { /** * * @Description: json給前台輸出排序后的數據 * @param @return * @param @throws Exception * @return JSONObject * @throws */ public JSONObject jsonSort(int roleCount ,int peopleCount ,int markCount) throws Exception; }
4.service業務邏輯處理實現類
package com.hsinfo.web.Demo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * * @Description: * @date 2018年7月21日,上午12:27:32 */ @Service @Transactional public class JsonDemoServiceImpl implements JsonDemoService { /** * * @Description: 排序后打印出json規定格式 * @param @return * @param @throws Exception * @throws */ @Override public JSONObject jsonSort(int roleCount ,int peopleCount ,int markCount) throws Exception { List<Role> roleList = SimulationData.dataRole(roleCount); List<People> peopleList = SimulationData.dataPeople(peopleCount, markCount); JSONObject returnJson = jsonStudy(peopleList,roleList); return returnJson; } /** * * @Description: 實戰使用,根據mark找People的相關Role且使用Json格式打印(可排序也可不排序) * 重點:學習JSONObject與JSONArray的使用(Json轉對象,對象轉Json) * @param @param peopleList * @param @param userList * @param @return * @return JSONObject * @throws */ private JSONObject jsonStudy(List<People> peopleList, List<Role> roleList) { long start = System.currentTimeMillis(); JSONObject returnJson = new JSONObject(); JSONArray peopleJsonArray = new JSONArray(); for (People people : peopleList) { //每個人的標記集合 Set<String> markSet = people.getMarkSet(); JSONObject propleJson = new JSONObject(); propleJson.put("description", "People數據信息如下:"); propleJson.put("message", people.getMessage()); JSONArray roleJsonArray = new JSONArray(); /**匹配每個人扮演的角色*/ for (String mark : markSet) { for (Role role : roleList) { if (mark.equals(role.getMark())) { JSONObject userDataJson = JSONObject.fromObject(role); userDataJson.put("description", "添加的屬性字段信息" + mark); roleJsonArray.add(userDataJson); } } } /**把JSONArray(roleJsonArray)轉換為List對象*/ if (roleJsonArray.size() > 0) { List<RoleJson> roleJonList = new ArrayList<RoleJson>(); for (int i = 0; i < roleJsonArray.size(); i++) { JSONObject roleJson = (JSONObject) roleJsonArray.get(i); RoleJson roleJsonDate = new RoleJson(); roleJsonDate = (RoleJson) JSONObject.toBean(roleJson, RoleJson.class); roleJonList.add(roleJsonDate); } /**根據唯一標記(mark)進行角色排序*/ Collections.sort(roleJonList, new Comparator<RoleJson>() { public int compare(RoleJson R1, RoleJson R2) { return (R1.getMark()).compareTo(R2.getMark()); } }); propleJson.put("roleJonList", roleJonList); peopleJsonArray.add(propleJson); } } /**多個人根據第一個標記進行排序輸出*/ if (peopleJsonArray.size() > 0) { List<PeopleJson> peopleJsonList = new ArrayList<PeopleJson>(); /**JSONArray(peopleDataJsonArray)轉換為Map對象*/ for (int i = 0; i < peopleJsonArray.size(); i++) { JSONObject pJsonObject = (JSONObject) peopleJsonArray.get(i); PeopleJson peopleJson = new PeopleJson(); Map<String, Class<RoleJson>> map = new HashMap<String, Class<RoleJson>>(); map.put("roleJonList", RoleJson.class); peopleJson = (PeopleJson) JSONObject.toBean(pJsonObject, PeopleJson.class, map); peopleJsonList.add(peopleJson); } /**排序*/ Collections.sort(peopleJsonList, new Comparator<PeopleJson>() { public int compare(PeopleJson R1, PeopleJson R2) { return R1.getRoleJonList().get(0).getMark().compareTo(R2.getRoleJonList().get(0).getMark()); } }); peopleJsonArray.add(peopleJsonList); returnJson.put("peopleJsonArray", peopleJsonList); } long end = System.currentTimeMillis(); System.out.println("處理數據時間:"+(end-start)); return returnJson; } }
5.service業務處理json轉換bean對象時,需要創建一個實體類,實體類屬性與json節點key值保持一致(不然會出現Bug),也就是Json對象中保存的節點與需要轉換為bean對象的實體類屬性保持一致
5.1.PeopleJson
package com.hsinfo.web.Demo; import java.util.List; /** * @Description:JSONArray所存儲的節點key值一致(必須與你所要輸出的Json格式的節點一致,不然會報錯) * 例: * "peopleDataJsonArray": [ { "description": "People數據信息如下:", "message": "kgeGn", "roleJonList": [ { "age": 87, "description": "添加的屬性字段信息0485833161", "mark": "0485833161", "name": "zXlMw", "sex": "JQ" }, ] }, ] * @date 2018年7月22日,下午8:47:59 */ public class PeopleJson { private String description; private String message; private List<RoleJson> roleJonList; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<RoleJson> getRoleJonList() { return roleJonList; } public void setRoleJonList(List<RoleJson> roleJonList) { this.roleJonList = roleJonList; } }
5.2.RoleJson
package com.hsinfo.web.Demo; /** * @Description: 作用和PeopleJson一樣 * @date 2018年7月22日,下午8:53:52 */ public class RoleJson { private String mark; private String name; private int age; private String sex; //json輸出需要這個節點且前台需要這個節點的值 private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
6.模擬數據信息
package com.hsinfo.web.Demo; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; /** * @Description:模擬數據信息 * 一個人可以有多個角色,例如:在家中是兒子,在學校是學生,在公司是程序員,一個人還可以辦好多業務 * 每個業務好多個人都可以辦,則標記(mark)就是記錄這唯一標識的(如id)業務和稱職 * @date 2018年7月22日,下午2:26:52 */ public class SimulationData { // 保存用戶賬戶的唯一標記 private static List<String> markLists = new ArrayList<String>(); /** * * @Description: user模擬數據 * @param @param userCount user對象個數 * @param @return * @return List<User> * @throws */ public static List<Role> dataRole(int roleCount) { long start = System.currentTimeMillis(); System.out.println("/**********************《start添加User信息內容》********************/"); List<Role> roleList = new ArrayList<Role>(); for (int i = 1; i <= roleCount; i++) { Role role = new Role(); String mark = RandomDemo.getRandom(10, RandomDemo.TYPE.NUMBER); markLists.add(mark); role.setMark(mark); role.setName(RandomDemo.getRandom(5, RandomDemo.TYPE.LETTER_CAPITAL)); Integer age = Integer.parseInt(RandomDemo.getRandom(2, RandomDemo.TYPE.NUMBER)); role.setAge(age); role.setSex(RandomDemo.getRandom(2, RandomDemo.TYPE.LETTER_CAPITAL)); roleList.add(role); } for (int i = 0; i < roleList.size(); i++) { System.out.println("第" + (i + 1) + "組User數據"); System.out.print(" " + "name:" + roleList.get(i).getName() + ",age:" + roleList.get(i).getAge() + ",sex:" + roleList.get(i).getSex() + ",mark:" + roleList.get(i).getMark()); System.out.println(); } long end = System.currentTimeMillis(); System.out.println("Role數據產生時間:"+(end-start)); System.out.println("/**********************《end添加User信息內容》********************/"); return roleList; } /** * * @Description: people模擬數據信息 * @param @param peopleCount people對象個數 * @param @param markCount 一個prople對應的標記個數 * @param @return * @return List<People> * @throws */ public static List<People> dataPeople(int peopleCount,int markCount) { System.out.println("/**********************《start添加People信息內容》********************/"); long start = System.currentTimeMillis(); List<People> peopleList = new ArrayList<People>(); for (int i = 1; i <= peopleCount; i++) { People people = new People(); people.setMessage(RandomDemo.getRandom(5, RandomDemo.TYPE.LETTER_CAPITAL)); // 去除重復的數字標記 Set<String> markSet = new HashSet<String>(); // 每個Prople類下有markCount個標記mark Random random = new Random(); for (int j = 1; j <= markCount; j++) { int n = random.nextInt(markLists.size()); markSet.add(markLists.get(n)); } people.setMarkSet(markSet); peopleList.add(people); } for (int i = 0; i < peopleList.size(); i++) { System.out.println("第" + (i + 1) + "組People數據"); System.out.print(" mark標記列表" + peopleList.get(i).getMarkSet().toString() + ",message:"+ peopleList.get(i).getMessage()); System.out.println(); } long end = System.currentTimeMillis(); System.out.println("People數據產生時間:"+(end-start)); System.out.println("/**********************《end添加People信息內容》********************/"); return peopleList; } }
7.隨機產生數據源信息
package com.hsinfo.web.Demo; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /** * 字符隨機生成類 */ public class RandomDemo { /** * 隨機產生類型枚舉 */ public static enum TYPE { /**小字符型*/ LETTER, /**大寫字符型*/ CAPITAL, /**數字型*/ NUMBER, /**大+小字符 型*/ LETTER_CAPITAL, /**小字符+數字 型*/ LETTER_NUMBER, /**大寫字符+數字*/ CAPITAL_NUMBER, /**大+小字符+數字 型*/ LETTER_CAPITAL_NUMBER, } private static String[] lowercase = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private static String[] capital = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; private static String[] number = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" }; // private static String[] number = { "1", "2", "3", "4", "5", "6", "7", "8", "9"}; /** * 靜態隨機數 */ private static Random random = new Random(); /** * 獲取隨機組合碼 * @param num 位數 * @param type 類型 * @type * <br>小寫字符型 LETTER, * <br>大寫字符型 CAPITAL, * <br>數字型 NUMBER, * <br>大+小字符型 LETTER_CAPITAL, * <br>小字符+數字 型 LETTER_NUMBER, * <br>大字符+數字 型 CAPITAL_NUMBER, * <br>大+小字符+數字 型 LETTER_CAPITAL_NUMBER, */ public static String getRandom(int num, TYPE type) { ArrayList<String> temp = new ArrayList<String>(); StringBuffer code = new StringBuffer(); switch (type) { case LETTER: temp.addAll(Arrays.asList(lowercase)); break; case CAPITAL: temp.addAll(Arrays.asList(capital)); break; case NUMBER: temp.addAll(Arrays.asList(number)); break; case LETTER_CAPITAL: temp.addAll(Arrays.asList(lowercase)); temp.addAll(Arrays.asList(capital)); break; case LETTER_NUMBER: temp.addAll(Arrays.asList(lowercase)); temp.addAll(Arrays.asList(number)); break; case CAPITAL_NUMBER: temp.addAll(Arrays.asList(capital)); temp.addAll(Arrays.asList(number)); break; case LETTER_CAPITAL_NUMBER: temp.addAll(Arrays.asList(lowercase)); temp.addAll(Arrays.asList(capital)); temp.addAll(Arrays.asList(number)); break; } for (int i = 0; i < num; i++) { code.append(temp.get(random.nextInt(temp.size()))); } return code.toString(); } // public static void main(String[] args) { // System.out.println(RandomDemo.getRandom(10, RandomDemo.TYPE.LETTER_CAPITAL)); // } }
8.Controller控制器
package com.hsinfo.web.Demo; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import net.sf.json.JSONObject; @Controller @RequestMapping("/testDemoAction") public class TestDemoAction { @Autowired private JsonDemoService jsonDemoService; @RequestMapping(params = "peopleDate") @ResponseBody public JSONObject peopleDate(HttpServletRequest request){ JSONObject returnJson = new JSONObject(); Integer roleCount = Integer.parseInt(request.getParameter("roleCount")); Integer peopleCount = Integer.parseInt(request.getParameter("peopleCount")); Integer markCount = Integer.parseInt(request.getParameter("markCount")); try { long start = System.currentTimeMillis(); JSONObject resultDate = jsonDemoService.jsonSort(roleCount, peopleCount, markCount); long end = System.currentTimeMillis(); // System.out.println("運行時間:"+ (end-start)); returnJson.put("data", resultDate); returnJson.put("session", true); returnJson.put("msg", "請求數據接口成功"); returnJson.put("運行時間:", (end-start)); } catch (Exception e) { e.printStackTrace(); returnJson.put("data", null); returnJson.put("session", false); returnJson.put("msg", "請求數據接口失敗"); } return returnJson; } }
運行結果Json格式:由於每次運行隨機產生的數據不定,所以每次運行數據都有不同
{
"msg": "請求數據接口成功",
"resultDate": {
"peopleJsonArray": [
{
"description": "People數據信息如下:",
"message": "ZrqDe",
"roleJonList": [
{
"age": 81,
"description": "添加的屬性字段信息0522150993",
"mark": "0522150993",
"name": "TmlCj",
"sex": "Gy"
},
{
"age": 64,
"description": "添加的屬性字段信息5271761787",
"mark": "5271761787",
"name": "EySZq",
"sex": "Df"
}
]
},
{
"description": "People數據信息如下:",
"message": "EEAUM",
"roleJonList": [
{
"age": 45,
"description": "添加的屬性字段信息6695587378",
"mark": "6695587378",
"name": "qYUyU",
"sex": "sI"
},
{
"age": 32,
"description": "添加的屬性字段信息9386286052",
"mark": "9386286052",
"name": "HijbI",
"sex": "Va"
}
]
},
{
"description": "People數據信息如下:",
"message": "WydtG",
"roleJonList": [
{
"age": 45,
"description": "添加的屬性字段信息6695587378",
"mark": "6695587378",
"name": "qYUyU",
"sex": "sI"
}
]
}
]
},
"session": true
}
總結:一般做web后台給前台處理后的數據大都是json格式,把數據以json的格式丟給前台,前台進行顯示處理,渲染
JSONObject:用法與Map很類似,key,value,鍵值對
JSONArray:用法與數組類似,可以添加任何數據類型