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总结
JSONObject:json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value} JSONArray:json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式 ...
- net.sf.json.JSONObject 和org.json.JSONObject 的差别
http://my.oschina.net/wangwu91/blog/340721 net.sf.json.JSONObject 和org.json.JSONObject 的差别. 一.创建jso ...
- net.sf.json.JSONOBJECT.fromObject 与 com.alibaba.fastjson.JSONObject.parseObject
文章待补充,先写写以下知识点好了. NULL值处理之 net.sf.json.JSONObject 和 com.alibaba.fastjson.JSONObject区别 JSON作为一个轻量级的文本 ...
- 使用JSONObject遇到的问题,java.lang.NoClassDefFoundError: net/sf/json/JSONObject
先是报 java.lang.NoClassDefFoundError: net/sf/json/JSONObject 这个错误, 打开项目属性找到java build path中的libaries,找 ...
- net.sf.json.JSONObject 和org.json.JSONObject
参考 net.sf.json.JSONObject 和org.json.JSONObject 的差别
- net.sf.json.JSONObject处理 "null" 字符串的一些坑
转: net.sf.json.JSONObject处理 "null" 字符串的一些坑 2018年05月02日 16:41:25 大白能 阅读数:7026 版权声明:本文为博主原 ...
- net.sf.json.JSONObject maven下载到了但是java后台一直用不了问题
需求,实体转JSON,然后用到JSONObject转JSON,但是我向下面这样引入,后台就是用不了,还是报红, <dependency> <groupId>net.sf.jso ...
- 记一次未解决的异常:java.lang.NoClassDefFoundError: net/sf/json/JSONObject
原因:Jetty会导致这个问题,Tomcat可以正常启动 一.异常产生现象 使用json-lib转换实体类/字符串,跑单元测试没问题,但是启动jetty后调用JSONArray.fromObjec ...
- Jetty+json-lib库抛异常的问题解决过程(java.lang.NoClassDefFoundError: net/sf/json/JSONObject)
一.之前抛异常是将json库改成了fastjson解决的,参见: http://www.cnblogs.com/gossip/p/5369670.html 异常信息: 二.解决步骤 ...
随机推荐
- PHP-SQL查询上升的温度
给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id. +---------+------------------+------------- ...
- stelller插件与background-attachment配合使用,制作滚动页面
stelller插件与background-attachment:fixed配合使用,制作滚动页面
- Let's Encryt免费SSL证书申请[我司方案]
Let's Encrypt颁发的证书是目前生产的大多数浏览器都信任的,您只需下载并运行Let's Encrypt客户端来生成一个证书即可. 在颁发证书之前,需要验证您的域名的所有权.首先,在您的主机上 ...
- 【JZOJ5433】图
description 有一个n个点A+B条边的无向连通图,有一变量x,每条边的权值都是一个关于x的简单多项式,其中有A条边的权值是k+x,另外B条边的权值是k-x,如果只保留权值形如k+x的边,那么 ...
- 跨域问题The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by t
withCredentials 属性 上面说到,CORS请求默认不发送Cookie和HTTP认证信息.如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow- ...
- JS 基本的介绍
JS中的注释 HTML的注释:<!—注释内容--> CSS注释:/* 注释 */ JavaScript的注释:// 或 /* 多行注释 */ 变量 1.变量的概念 变量是变化 ...
- js中一个标签在按顺序执行没有被读取到时可以用window.onload
<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%> <!DOCTYPE html PUBLIC " ...
- 猥琐发育,3月份Java干货已到达战场!
时间真的过得很快,又是月底了,又到了我们总结这个月干货的时候了.3月份这个月我们都带来了哪些干货呢?我们一起回顾一下. 坑爹,手机端链接点不开,请切换到电脑端或者关注我们的微信公众号进行阅读. 扫描关 ...
- 大型SQL文件导入mysql方案
一. 场景 现有俩个体积较大的单表sql文件,一个为8G,一个为4G,要在一天内完整导入到阿里云的mysql中,需要同时蛮子时间和空间这俩种要求. 二. 思路 搜索了网上一堆的方案,总结了如下几个: ...
- 基于jdk8的格式化时间方法
背景 jdk8之前,java使用Date表示时间,在做时间的格式化时,通常使用SimpleDateFormat,但是SimpleDateFormat是非线程安全的,在写代码时通常要将之定义为局部变量或 ...