net.sf.json JSONObject与JSONArray使用实例
Posted A小小高
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了net.sf.json JSONObject与JSONArray使用实例相关的知识,希望对你有一定的参考价值。
实例自己想的一个实例应用场景:一个人可以有多个角色,例如:在家中是儿子,在学校是学生,在公司是程序员,一个人还可以办好多业务
* 每个业务好多个人都可以办,则标记(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:用法与数组类似,可以添加任何数据类型
以上是关于net.sf.json JSONObject与JSONArray使用实例的主要内容,如果未能解决你的问题,请参考以下文章
net.sf.json JSONObject与JSONArray使用实例
net.sf.json.JSONObject 和org.json.JSONObject 的差别
net.sf.json.JSONObject 和org.json.JSONObject 的差别
未找到 Java 类型、net.sf.json.JSONObject 类和 MIME 媒体类型 application/json 的消息正文编写器
急!ssh+json 空指针异常(net.sf.json.JSONException: java.lang.NullPointerException)