下面列出了com.alibaba.fastjson.JSONArray#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping("group-list")
public void groupList(HttpServletRequest request, HttpServletResponse response) throws IOException {
final ID user = getRequestUser(request);
final String query = getParameter(request, "q");
Set<Team> teams = Application.getUserStore().getUser(user).getOwningTeams();
JSONArray ret = new JSONArray();
for (Team t : teams) {
if (StringUtils.isBlank(query)
|| StringUtils.containsIgnoreCase(t.getName(), query)) {
JSONObject o = JSONUtils.toJSONObject(
new String[] { "id", "name" }, new Object[] { t.getIdentity(), t.getName() });
ret.add(o);
if (ret.size() >= 20) {
break;
}
}
}
writeSuccess(response, ret);
}
@RequestMapping("/clientlogin")
@ResponseBody
public String login( HttpSession httpSession, String email, String password) {
JSONArray jsonArray = new JSONArray();
String basepass = Base64Encryption.encryptBASE64(password.getBytes());
Integer ret = userService.login(email, basepass,null);
if (ret > 0) {
User user = userService.getUsers(email);
if (user.getIsok() == 1) {
jsonArray.add(1);
} else if(ret==-1){
jsonArray.add(-1);
}else {
jsonArray.add(-2);
}
} else {
jsonArray.add(0);
}
return jsonArray.toString();
}
/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static JSONArray readTxtFile(String filePath){
try {
String encoding="UTF-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
JSONArray jsonArray=new JSONArray();
while((lineTxt = bufferedReader.readLine()) != null){
jsonArray.add(lineTxt);
}
read.close();
return jsonArray;
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return null;
}
/**
* 查找会员信息-下拉框
* @param request
* @return
*/
@PostMapping(value = "/findBySelect_retail")
public JSONArray findBySelectRetail(HttpServletRequest request)throws Exception {
JSONArray arr = new JSONArray();
try {
List<Supplier> supplierList = supplierService.findBySelectRetail();
JSONArray dataArray = new JSONArray();
if (null != supplierList) {
for (Supplier supplier : supplierList) {
JSONObject item = new JSONObject();
item.put("id", supplier.getId());
//客户名称
item.put("supplier", supplier.getSupplier());
item.put("advanceIn", supplier.getAdvancein()); //预付款金额
dataArray.add(item);
}
}
arr = dataArray;
} catch(Exception e){
e.printStackTrace();
}
return arr;
}
@Test
public void testParseCreateExternalTable_withoutTableComment() throws Exception {
TestTableProvider tableProvider = new TestTableProvider();
BeamSqlEnv env = BeamSqlEnv.withTableProvider(tableProvider);
JSONObject properties = new JSONObject();
JSONArray hello = new JSONArray();
hello.add("james");
hello.add("bond");
properties.put("hello", hello);
env.executeDdl(
"CREATE EXTERNAL TABLE person (\n"
+ "id int COMMENT 'id', \n"
+ "name varchar COMMENT 'name') \n"
+ "TYPE 'text' \n"
+ "LOCATION '/home/admin/person'\n"
+ "TBLPROPERTIES '{\"hello\": [\"james\", \"bond\"]}'");
assertEquals(
mockTable("person", "text", null, properties), tableProvider.getTables().get("person"));
}
@Override
public JSON execute(ApiContext context) throws ApiInvokeException {
String entity = context.getParameterNotBlank("entity");
if (!MetadataHelper.containsEntity(entity)) {
throw new ApiInvokeException("Unknow entity : " + entity);
}
Entity thatEntity = MetadataHelper.getEntity(entity);
JSONArray array = new JSONArray();
for (Field field : thatEntity.getFields()) {
if (MetadataHelper.isSystemField(field) || !field.isQueryable()) {
continue;
}
array.add(buildField(field));
}
return formatSuccess(array);
}
public static JSONArray rSToJson(ResultSet rs) throws SQLException, JSONException
{
JSONArray array = new JSONArray();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
JSONObject jsonObj = new JSONObject();
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
String value = rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.add(jsonObj);
}
return array;
}
private void createJsonObjectButton(JSONArray button, WechatMenu content) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", content.getType());
jsonObject.put("name", content.getText());
//跳转网页
if ("view".equals(content.getType())) {
jsonObject.put("url", content.getKeyword());
}
//跳转微信小程序
else if ("miniprogram".equals(content.getType())) {
String[] appIdAndPage = content.getKeyword().split(":");
jsonObject.put("appid", appIdAndPage[0]);
jsonObject.put("pagepath", appIdAndPage[1]);
jsonObject.put("url", getBaseUrl());
}
//其他
else {
jsonObject.put("key", content.getKeyword());
}
button.add(jsonObject);
}
private void appendChildren(ID itemId, JSONObject into, int level) {
if (level > openLevel) {
return;
}
Object[][] array = Application.createQueryNoFilter(
"select itemId,name from ClassificationData where dataId = ? and parent = ?")
.setParameter(1, dataId)
.setParameter(2, itemId)
.array();
JSONArray children = new JSONArray();
for (Object[] o : array) {
JSONObject item = buildItem(o);
appendChildren((ID) o[0], item, level + 1);
children.add(item);
}
into.put("children", children);
}
/**
* 获取支行信息
*/
@RequestMapping(value = "/branchList", produces = "application/json;charset=UTF-8")
@ResponseBody
public JSONArray getBranchList(HttpServletRequest request, BankType bankType, String cityCode, String keyWord) {
keyWord = keyWord == null ? "" : keyWord;
List<IndexModel> list = bankService.queryBrank(cityCode, bankType, keyWord);
JSONArray array = new JSONArray();
if (list != null) {
for (IndexModel item : list) {
JSONObject json = new JSONObject();
json.put("label", item.getIndexBody());
json.put("value", item.getIndexBody());
array.add(json);
}
}
// {label:"中国银行广州支行",value:"中国银行广州支行"}
return array;
}
public static void main(String[] args) {
TestFastJson entity=new TestFastJson();
JSONObject json=new JSONObject();
JSONArray list=new JSONArray();
list.add(1);
json.put("1", 1);
json.put("list",list);
entity.setJson(json);
String jsonStr=JSON.toJSONString(entity);
System.out.println(jsonStr);
entity=JSONObject.parseObject(jsonStr,TestFastJson.class);
System.out.println(entity);
//反序列化
DefaultJSONParser jp=new DefaultJSONParser(jsonStr);
JSONObject json2=jp.parseObject();
System.out.println("id:"+json2.getIntValue("id"));
//类型反序列化
Type type=new TypeReference<TestFastJson>() {
}.getType();
TestFastJson entity2=JSON.parseObject(jsonStr, type);
System.out.println(entity2.getId());
}
@RequestMapping("symbol-thumb-trend")
public JSONArray findSymbolThumbWithTrend(){
List<ExchangeCoin> coins = coinService.findAllEnabled();
//List<CoinThumb> thumbs = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
//将秒、微秒字段置为0
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.MINUTE,0);
long nowTime = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR_OF_DAY,-24);
JSONArray array = new JSONArray();
long firstTimeOfToday = calendar.getTimeInMillis();
for(ExchangeCoin coin:coins){
CoinProcessor processor = coinProcessorFactory.getProcessor(coin.getSymbol());
CoinThumb thumb = processor.getThumb();
JSONObject json = (JSONObject) JSON.toJSON(thumb);
json.put("zone",coin.getZone());
List<KLine> lines = marketService.findAllKLine(thumb.getSymbol(),firstTimeOfToday,nowTime,"1hour");
JSONArray trend = new JSONArray();
for(KLine line:lines){
trend.add(line.getClosePrice());
}
json.put("trend",trend);
array.add(json);
}
return array;
}
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("FIRST NAME", "John" + i);
jsonObject.put("LAST NAME", "Doe" + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
}
@Request(opcode = Cmd.BagInfo)
public JSONObject BagInfo(JSONObject req, Session session) {
List<BagItem> bagItemList = dataService.selectList(BagItem.class,"uid=?",session.getUid());
JSONObject ret = new JSONObject();
JSONArray array = new JSONArray();
for(BagItem bagItem : bagItemList){
array.add(bagItem.toJson());
}
ret.put("bagItems",array);
return ret;
}
public void read() throws IOException {
InputStream fileInputStream = new FileInputStream("/mnt/hgfs/share/ppt/6635.pptx");
JSONObject object = pptx.read(fileInputStream, this);
fileInputStream.close();
JSONArray array=new JSONArray();
array.add(object);
io.write("/mnt/hgfs/share/ppt/import.json", array.toJSONString().getBytes());
}
@Override
public JSONArray getJeecgMenu(String id) throws Exception {
List<SysPermission> metaList = sysPermissionService.queryByUser(id);
JSONArray jsonArray = new JSONArray();
getPermissionJsonArray(jsonArray, metaList, null);
JSONArray menulist= parseNgAlain(jsonArray);
JSONObject jeecgMenu = new JSONObject();
jeecgMenu.put("text", "jeecg菜单");
jeecgMenu.put("group",true);
jeecgMenu.put("children", menulist);
JSONArray jeecgMenuList=new JSONArray();
jeecgMenuList.add(jeecgMenu);
return jeecgMenuList;
}
/**
* 构造使用Token方式访问服务的请求Token对象
*
* @param username 用户名
* @param passwd 密码
* @param domainName 域名
* @param projectName 项目名称
* @return 构造访问的JSON对象
*/
private static String requestBody(String username, String passwd, String domainName, String projectName) {
JSONObject auth = new JSONObject();
JSONObject identity = new JSONObject();
JSONArray methods = new JSONArray();
methods.add("password");
identity.put("methods", methods);
JSONObject password = new JSONObject();
JSONObject user = new JSONObject();
user.put("name", username);
user.put("password", passwd);
JSONObject domain = new JSONObject();
domain.put("name", domainName);
user.put("domain", domain);
password.put("user", user);
identity.put("password", password);
JSONObject scope = new JSONObject();
JSONObject scopeProject = new JSONObject();
scopeProject.put("name", projectName);
scope.put("project", scopeProject);
auth.put("identity", identity);
auth.put("scope", scope);
JSONObject params = new JSONObject();
params.put("auth", auth);
return params.toJSONString();
}
@RequestMapping("/chart-save")
public void chartSave(HttpServletRequest request, HttpServletResponse response) throws IOException {
ID user = getRequestUser(request);
JSON formJson = ServletUtils.getRequestJson(request);
Record record = EntityHelper.parse((JSONObject) formJson, user);
ID dashid = null;
if (record.getPrimary() == null) {
dashid = getIdParameterNotNull(request, "dashid");
}
record = Application.getBean(ChartConfigService.class).createOrUpdate(record);
// 添加到仪表盘
if (dashid != null) {
Object[] dash = Application.createQueryNoFilter(
"select config from DashboardConfig where configId = ?")
.setParameter(1, dashid)
.unique();
JSONArray config = JSON.parseArray((String) dash[0]);
JSONObject item = JSONUtils.toJSONObject("chart", record.getPrimary());
item.put("w", 4);
item.put("h", 4);
config.add(item);
Record dashRecord = EntityHelper.forUpdate(dashid, getRequestUser(request));
dashRecord.setString("config", config.toJSONString());
Application.getBean(DashboardConfigService.class).createOrUpdate(dashRecord);
}
JSONObject ret = JSONUtils.toJSONObject("id", record.getPrimary());
writeSuccess(response, ret);
}
@Override
public JSONArray getJeecgMenu(String id) throws Exception {
List<SysPermission> metaList = sysPermissionService.queryByUser(id);
JSONArray jsonArray = new JSONArray();
getPermissionJsonArray(jsonArray, metaList, null);
JSONArray menulist= parseNgAlain(jsonArray);
JSONObject jeecgMenu = new JSONObject();
jeecgMenu.put("text", "jeecg菜单");
jeecgMenu.put("group",true);
jeecgMenu.put("children", menulist);
JSONArray jeecgMenuList=new JSONArray();
jeecgMenuList.add(jeecgMenu);
return jeecgMenuList;
}
/**
* 根据任务名称或任务ID模糊查询
*
* @return
*/
public String searchTaskByNameOrId(HttpServletRequest request) {
String ftpItemJson = request.getParameter("ftpItemJson");
JSONObject ftpItemJsonObj = null;
try {
// 校验格式是否正确
// {"taskName":"经办人照片同步处理"}
ftpItemJsonObj = JSONObject.parseObject(ftpItemJson);
} catch (Exception e) {
logger.error("传入参数格式不正确:" + ftpItemJson, e);
resultMsg = createResultMsg("1999", "传入参数格式不正确:" + ftpItemJson, "");
return "addFtpItem";
}
// 将ftpItemJson装为Map保存操作
Map paramIn = JSONObject.parseObject(ftpItemJsonObj.toJSONString(), Map.class);
String taskNameOrTaskId = paramIn.get("taskName") == null ? "1" : paramIn.get("taskName").toString();
taskNameOrTaskId = ValidatorUtils.getValueAsString(paramIn, "taskName");
// 规则校验
JSONObject data = new JSONObject();
data.put("total", 1); // 搜索不进行分页处理
data.put("currentPage", 1);
List<Map> ftpItems = null;
// 说明是taskId
if (GenericValidator.isInt(taskNameOrTaskId) || GenericValidator.isLong(taskNameOrTaskId)) {
// 根据taskId 查询记录
paramIn.put("taskId", taskNameOrTaskId);
Map ftpItem = iHcFtpFileDAO.queryFtpItemByTaskId(paramIn);
if (ftpItem != null && ftpItem.containsKey("FTP_ITEM_ATTRS")) {
ftpItem.remove("FTP_ITEM_ATTRS");// 前台暂时用不到,所以这里将属性移除
ftpItems = new ArrayList<Map>();
ftpItems.add(ftpItem);
}
} else {
ftpItems = iHcFtpFileDAO.searchFtpItemByTaskName(paramIn);
}
JSONArray rows = new JSONArray();
if (ftpItems != null && ftpItems.size() > 0) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (Map ftpItemMap : ftpItems) {
// 处理时间显示和界面显示传输类型
ftpItemMap.put("U_OR_D_NAME", ftpItemMap.get("U_OR_D"));// 暂且写死,最终还是读取配置
ftpItemMap.put("CREATE_DATE", df.format(ftpItemMap.get("CREATE_DATE")));// 暂且写死,最终还是读取配置
rows.add(JSONObject.parseObject(JSONObject.toJSONString(ftpItemMap)));
}
}
data.put("rows", rows);
resultMsg = data;
return "searchTaskByNameOrId";
}