Java Code Examples for com.alibaba.fastjson.JSONObject#put()

The following examples show how to use com.alibaba.fastjson.JSONObject#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtManager.java    From Mars-Java with MIT License 6 votes vote down vote up
/**
 * 根据Token获取存进去的对象
 * @param token
 * @param cls
 * @param <T>
 * @return obj
 */
public <T> T  getObject(String token,Class<T> cls) {
    JSONObject json = new JSONObject();
    try {
        Map<String, Claim> claims = decryptToken(token);
        if(claims == null || claims.isEmpty()){
            return null;
        }
        for (String key : claims.keySet()) {
            json.put(key, claims.get(key).asString());
        }
        return json.toJavaObject(cls);
    } catch (Exception e) {
        return null;
    }
}
 
Example 2
Source File: JeecgElasticsearchTemplate.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * @return { "bool" : { "must": must, "must_not": mustNot, "should": should } }
 */
public JSONObject buildBoolQuery(JSONArray must, JSONArray mustNot, JSONArray should) {
    JSONObject bool = new JSONObject();
    if (must != null) {
        bool.put("must", must);
    }
    if (mustNot != null) {
        bool.put("must_not", mustNot);
    }
    if (should != null) {
        bool.put("should", should);
    }
    JSONObject json = new JSONObject();
    json.put("bool", bool);
    return json;
}
 
Example 3
Source File: NumberProperty.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String,Object> getPropertyJson() {
	Map<String,Object> map = new HashMap<>();
	map.put("key",getKey());
	JSONObject prop = getCommonJson();
	if(multipleOf!=null) {
		prop.put("multipleOf",multipleOf);
	}
	if(maxinum!=null) {
		prop.put("maxinum",maxinum);
	}
	if(exclusiveMaximum!=null) {
		prop.put("exclusiveMaximum",exclusiveMaximum);
	}
	if(minimum!=null) {
		prop.put("minimum",minimum);
	}
	if(exclusiveMinimum!=null) {
		prop.put("exclusiveMinimum",exclusiveMinimum);
	}
	if(pattern!=null) {
		prop.put("pattern",pattern);
	}
	map.put("prop",prop);
	return map;
}
 
Example 4
Source File: LoginController.java    From jeecg with Apache License 2.0 6 votes vote down vote up
public JSONArray getChildOfAdminLteTree(TSFunction function) {
	JSONArray jsonArray = new JSONArray();
	List<TSFunction> functions = this.systemService.findByProperty(TSFunction.class, "TSFunction.id", function.getId());
	if(functions != null && functions.size() > 0) {
		for (TSFunction tsFunction : functions) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", tsFunction.getId());
			jsonObject.put("text", MutiLangUtil.getLang(tsFunction.getFunctionName()));
			jsonObject.put("url", tsFunction.getFunctionUrl());
			jsonObject.put("targetType", "iframe-tab");
			jsonObject.put("icon", "fa " + tsFunction.getFunctionIconStyle());
			jsonObject.put("children", getChildOfAdminLteTree(tsFunction));
			jsonArray.add(jsonObject);
		}
	}
	return jsonArray;
}
 
Example 5
Source File: ESUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public boolean saveMemberTransaction(MemberTransaction memberTransaction,String esIndex,String esType){
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id",memberTransaction.getId());
    jsonObject.put("address",memberTransaction.getAddress());
    jsonObject.put("amount",memberTransaction.getAmount());
    jsonObject.put("create_time",DateUtil.dateToString(memberTransaction.getCreateTime()));
    jsonObject.put("fee",memberTransaction.getFee());
    jsonObject.put("flag",memberTransaction.getFlag());
    jsonObject.put("member_id",memberTransaction.getMemberId());
    jsonObject.put("symbol",memberTransaction.getSymbol());
    jsonObject.put("type",TransactionType.parseOrdinal(memberTransaction.getType()));
    jsonObject.put("real_fee",new BigDecimal(memberTransaction.getRealFee()));
    jsonObject.put("discount_fee",new BigDecimal(memberTransaction.getDiscountFee()));
    log.info("===存入ES 数据==="+jsonObject);
    boolean result = saveForAnyOne(jsonObject,esIndex,esType);
    if (result == true){
        return true;
    }
    return false;
}
 
Example 6
Source File: AccountHeadController.java    From jshERP with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 查询单位的累计应收和累计应付,收预付款不计入此处
 * @param supplierId
 * @param endTime
 * @param supType
 * @param request
 * @return
 */
@GetMapping(value = "/findTotalPay")
public BaseResponseInfo findTotalPay(@RequestParam("supplierId") Integer supplierId,
                                     @RequestParam("endTime") String endTime,
                                     @RequestParam("supType") String supType,
                                     HttpServletRequest request)throws Exception {
    BaseResponseInfo res = new BaseResponseInfo();
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        JSONObject outer = new JSONObject();
        BigDecimal sum = accountHeadService.findTotalPay(supplierId, endTime, supType);
        outer.put("getAllMoney", sum);
        map.put("rows", outer);
        res.code = 200;
        res.data = map;
    } catch (Exception e) {
        e.printStackTrace();
        res.code = 500;
        res.data = "获取数据失败";
    }
    return res;
}
 
Example 7
Source File: AgentCacheManageController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 缓存信息
 *
 * @return json
 */
@RequestMapping(value = "cache", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String cache() {
    JSONObject jsonObject = new JSONObject();
    //
    File file = ConfigBean.getInstance().getTempPath();
    String fileSize = FileUtil.readableFileSize(FileUtil.size(file));
    jsonObject.put("fileSize", fileSize);
    //
    jsonObject.put("pidName", AbstractProjectCommander.PID_JPOM_NAME.size());
    jsonObject.put("pidPort", AbstractProjectCommander.PID_PORT.size());

    int oneLineCount = AgentFileTailWatcher.getOneLineCount();
    jsonObject.put("readFileOnLineCount", oneLineCount);
    //
    jsonObject.put("pidError", JvmUtil.PID_ERROR.size());
    return JsonMessage.getString(200, "ok", jsonObject);
}
 
Example 8
Source File: DataFlow.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
public DataFlow builderByBusiness(String businessInfo) throws Exception{
    try{
        Business business = null;
        JSONObject reqInfoObj = JSONObject.parseObject(businessInfo);
        this.setReqJson(reqInfoObj);
        this.setReqData(businessInfo);
        this.setDataFlowId(reqInfoObj.containsKey("dataFlowId")?reqInfoObj.getString("dataFlowId"):"-1");
        //this.setAppId(orderObj.getString("appId"));
        this.setTransactionId(reqInfoObj.getString("transactionId"));
        this.setOrderTypeCd(reqInfoObj.getString("orderTypeCd"));
        this.setRequestTime(reqInfoObj.getString("responseTime"));
        this.setBusinessType(reqInfoObj.getString("businessType"));
        //this.setReqOrders(orderObj);
        JSONObject businessObj = new JSONObject();
        businessObj.put("bId",reqInfoObj.getString("bId"));
        businessObj.put("serviceCode",reqInfoObj.getString("serviceCode"));
        JSONArray reqBusinesses = new JSONArray();
        reqBusinesses.add(businessInfo);
        this.setReqBusiness(reqBusinesses);
        JSONObject response = reqInfoObj.getJSONObject("response");
        this.setCode(response.getString("code"));
        this.setMessage(response.getString("message"));
        businessObj.put("response",response);
        this.businesses = new ArrayList<Business>();
        business = new Business().builder(businessObj);
        businesses.add(business);
        this.setCurrentBusiness(business);
    }catch (Exception e){

        throw e;
    }
    return this;
}
 
Example 9
Source File: AbstractResourceStoreBusinessServiceDataFlowListener.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
     * 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
     *
     * @param businessResourceStore 资源信息
     */
    protected void autoSaveDelBusinessResourceStore(Business business, JSONObject businessResourceStore) {
//自动插入DEL
        Map info = new HashMap();
        info.put("resId", businessResourceStore.getString("resId"));
        info.put("statusCd", StatusConstant.STATUS_CD_VALID);
        List<Map> currentResourceStoreInfos = getResourceStoreServiceDaoImpl().getResourceStoreInfo(info);
        if (currentResourceStoreInfos == null || currentResourceStoreInfos.size() != 1) {
            throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
        }

        Map currentResourceStoreInfo = currentResourceStoreInfos.get(0);

        currentResourceStoreInfo.put("bId", business.getbId());

        currentResourceStoreInfo.put("resName", currentResourceStoreInfo.get("res_name"));
        currentResourceStoreInfo.put("operate", currentResourceStoreInfo.get("operate"));
        currentResourceStoreInfo.put("price", currentResourceStoreInfo.get("price"));
        currentResourceStoreInfo.put("resCode", currentResourceStoreInfo.get("res_code"));
        currentResourceStoreInfo.put("description", currentResourceStoreInfo.get("description"));
        currentResourceStoreInfo.put("storeId", currentResourceStoreInfo.get("store_id"));
        currentResourceStoreInfo.put("stock", currentResourceStoreInfo.get("stock"));
        currentResourceStoreInfo.put("resId", currentResourceStoreInfo.get("res_id"));


        currentResourceStoreInfo.put("operate", StatusConstant.OPERATE_DEL);
        getResourceStoreServiceDaoImpl().saveBusinessResourceStoreInfo(currentResourceStoreInfo);

        for (Object key : currentResourceStoreInfo.keySet()) {
            if (businessResourceStore.get(key) == null) {
                businessResourceStore.put(key.toString(), currentResourceStoreInfo.get(key));
            }
        }
    }
 
Example 10
Source File: TradePlate.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public JSONObject toJSON(int limit){
    JSONObject json = new JSONObject();
    json.put("direction",direction);
    json.put("maxAmount",getMaxAmount());
    json.put("minAmount",getMinAmount());
    json.put("highestPrice",getHighestPrice());
    json.put("lowestPrice",getLowestPrice());
    json.put("symbol",getSymbol());
    json.put("items",items.size() > limit ? items.subList(0,limit) : items);
    return json;
}
 
Example 11
Source File: ServiceResult.java    From Ffast-Java with MIT License 5 votes vote down vote up
public String toJSON() {
    JSONObject result = new JSONObject();
    result.put("message", message);
    result.put("success", success);
    result.put("data", data);
    result.put("errNo", errNo);
    return result.toString();
}
 
Example 12
Source File: ListenerExecuteException.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 异常
 * @return
 */
public String toJsonString() {
    JSONObject exceptionJson = JSONObject.parseObject("{\"exception\":{}");
    JSONObject exceptionJsonObj = exceptionJson.getJSONObject("exception");

    if (getResult() != null)
        exceptionJsonObj.putAll(JSONObject.parseObject(result.toString()));

    exceptionJsonObj.put("exceptionTrace",getMessage());

    return exceptionJsonObj.toString();
}
 
Example 13
Source File: EditOwnerRepairSMOImpl.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) {
    ResponseEntity<String> responseEntity = null;
    super.validateStoreStaffCommunityRelationship(pd, restTemplate);

    JSONObject newParamIn = new JSONObject();
    newParamIn.put("communityId", paramIn.getString("communityId"));
    newParamIn.put("repairId", paramIn.getString("repairId"));
    newParamIn.put("page", 1);
    newParamIn.put("row", 1);

    //查询保修状态
    String apiUrl = ServiceConstant.SERVICE_API_URL + "/api/ownerRepair.listOwnerRepairs" + mapToUrlParam(newParamIn);
    responseEntity = this.callCenterService(restTemplate, pd, "",
            apiUrl,
            HttpMethod.GET);

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        return responseEntity;
    }
    JSONObject outRepairInfo = JSONObject.parseObject(responseEntity.getBody());
    JSONObject repairObj = outRepairInfo.getJSONArray("ownerRepairs").getJSONObject(0);
    paramIn.put("state", repairObj.getString("state"));
    responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(),
            ServiceConstant.SERVICE_API_URL + "/api/ownerRepair.updateOwnerRepair",
            HttpMethod.POST);
    return responseEntity;
}
 
Example 14
Source File: GroupController.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * Health cluster number and bad cluster number calculating from cluster list info
 *
 * @param groupId
 * @return
 */
@RequestMapping(value = "/overview/{groupId}", method = RequestMethod.GET)
@ResponseBody
public Result getGroupPartOverview(@PathVariable("groupId") Integer groupId) {
    JSONObject overview = new JSONObject();
    overview.put(USER_NUMBER, userService.getUserNumber(groupId));
    overview.put(ALERT_NUMBER, alertRecordService.getAlertRecordNumber(groupId));
    return Result.successResult(overview);
}
 
Example 15
Source File: SaveStoreInfoListener.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 保存 商户证件 信息
 *
 * @param business                   当前业务
 * @param businessStoreCerdentialses 商户证件
 */
private void doBusinessStoreCerdentials(Business business, JSONArray businessStoreCerdentialses) {
    for (int businessStoreCerdentialsIndex = 0; businessStoreCerdentialsIndex < businessStoreCerdentialses.size(); businessStoreCerdentialsIndex++) {
        JSONObject businessStoreCerdentials = businessStoreCerdentialses.getJSONObject(businessStoreCerdentialsIndex);
        Assert.jsonObjectHaveKey(businessStoreCerdentials, "storeId", "businessStorePhoto 节点下没有包含 storeId 节点");

        if (businessStoreCerdentials.getString("storeCerdentialsId").startsWith("-")) {
            String storePhotoId = GenerateCodeFactory.getStoreCerdentialsId();
            businessStoreCerdentials.put("storeCerdentialsId", storePhotoId);
        }
        Date validityPeriod = null;
        try {
            if (StringUtil.isNullOrNone(businessStoreCerdentials.getString("validityPeriod"))) {
                validityPeriod = DateUtil.getLastDate();
            } else {
                validityPeriod = DateUtil.getDateFromString(businessStoreCerdentials.getString("validityPeriod"), DateUtil.DATE_FORMATE_STRING_B);
            }
        } catch (ParseException e) {
            throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "传入参数 validityPeriod 格式不正确,请填写 " + DateUtil.DATE_FORMATE_STRING_B + " 格式," + businessStoreCerdentials);
        }
        businessStoreCerdentials.put("validityPeriod", validityPeriod);
        businessStoreCerdentials.put("bId", business.getbId());
        businessStoreCerdentials.put("operate", StatusConstant.OPERATE_ADD);
        //保存商户信息
        storeServiceDaoImpl.saveBusinessStoreCerdentials(businessStoreCerdentials);
    }
}
 
Example 16
Source File: HttpServer.java    From meshchain with Apache License 2.0 5 votes vote down vote up
private String getResponse(int code, String data, String message) {
    JSONObject rsp = JSON.parseObject("{}");
    rsp.put("code", code);
    rsp.put("data", data);
    rsp.put("message", message);
    return rsp.toJSONString();
}
 
Example 17
Source File: ClientListController.java    From RCT with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = { "monitor/check_job" }, method = RequestMethod.POST)
public RestResponse checkJob(@RequestParam String id) {
	JSONObject json = new JSONObject();
	if (AppCache.taskList.containsKey(String.valueOf(id))) {
		json.put("status", "ISRUNNING");
		Map<ScheduledFuture<?>,String> map = AppCache.taskList.get(String.valueOf(id));
		map.forEach((k,v)->{
			JSONObject res = JSONObject.parseObject((String)v);
			json.put("data", res);
		});
		
	} 
	return SUCCESS_DATA(json);
}
 
Example 18
Source File: SocialDetailActivity.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * 点赞
 * 
 */
public void setGood(String sID, TextView tv_good, JSONArray jsons,
        LinearLayout ll_goodmembers_temp, View view, int cSize) {
    // 即时改变当前UI
    JSONObject json = new JSONObject();
    json.put("userID", myuserID);
    jsons.add(json);
    setGoodTextClick(tv_good, jsons, ll_goodmembers_temp, view, cSize);
    // 更新后台
    Map<String, String> map = new HashMap<String, String>();
    map.put("sID", sID);

    map.put("userID", myuserID);

    SocialApiTask task = new SocialApiTask(SocialDetailActivity.this,
            Constant.URL_SOCIAL_GOOD, map);
    task.getData(new DataCallBack() {

        @Override
        public void onDataCallBack(JSONObject data) {
            // dialog.dismiss();
            if (data == null) {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----ERROR");
                return;
            }
            int code = data.getInteger("code");
            if (code == 1000) {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----SUCCESS");
            } else {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----ERROR_2");

            }
        }
    });

}
 
Example 19
Source File: WebsocketRequestImpl.java    From huobi_Java with Apache License 2.0 4 votes vote down vote up
WebsocketRequest<OrderListEvent> requestOrderDetailEvent(
    Long orderId,
    SubscriptionListener<OrderListEvent> subscriptionListener,
    SubscriptionErrorHandler errorHandler) {
  WebsocketRequest<OrderListEvent> request = new WebsocketRequest<>(subscriptionListener, errorHandler);

  InputChecker.checker().shouldNotNull(orderId, "orderId");
  request.name = "Order Detail Req for " + orderId;

  request.authHandler = (connection) -> {

    JSONObject requestTopic = new JSONObject();
    requestTopic.put("op", Channels.OP_REQ);
    requestTopic.put("topic", "orders.detail");
    requestTopic.put("order-id", orderId.toString());

    connection.send(requestTopic.toJSONString());
  };
  request.jsonParser = (jsonWrapper) -> {
    String ch = jsonWrapper.getString("topic");
    OrderListEvent listEvent = new OrderListEvent();
    listEvent.setTopic(ch);
    listEvent.setTimestamp(jsonWrapper.getLong("ts"));

    JsonWrapper item = jsonWrapper.getJsonObject("data");
    List<Order> orderList = new ArrayList<>();

    Order order = new Order();
    order.setAccountType(AccountsInfoMap.getAccount(apiKey, item.getLong("account-id")).getType());
    order.setAmount(item.getBigDecimal("amount"));
    order.setCanceledTimestamp(item.getLongOrDefault("canceled-at", 0));
    order.setFinishedTimestamp(item.getLongOrDefault("finished-at", 0));
    order.setOrderId(item.getLong("id"));
    order.setSymbol(item.getString("symbol"));
    order.setPrice(item.getBigDecimal("price"));
    order.setCreatedTimestamp(item.getLong("created-at"));
    order.setType(OrderType.lookup(item.getString("type")));
    order.setFilledAmount(item.getBigDecimal("filled-amount"));
    order.setFilledCashAmount(item.getBigDecimal("filled-cash-amount"));
    order.setFilledFees(item.getBigDecimal("filled-fees"));
    order.setSource(OrderSource.lookup(item.getString("source")));
    order.setState(OrderState.lookup(item.getString("state")));
    order.setStopPrice(item.getBigDecimalOrDefault("stop-price", null));
    order.setOperator(StopOrderOperator.find(item.getStringOrDefault("operator", null)));

    orderList.add(order);

    listEvent.setOrderList(orderList);
    return listEvent;
  };
  return request;
}
 
Example 20
Source File: AVFile.java    From java-unified-sdk with Apache License 2.0 4 votes vote down vote up
private Observable<AVFile> saveWithProgressCallback(boolean keepFileName, final ProgressCallback callback) {
  JSONObject paramData = generateChangedParam();
  final String fileKey = FileUtil.generateFileKey(this.getName(), keepFileName);
  paramData.put("key", fileKey);
  paramData.put("__type", "File");
  if (StringUtil.isEmpty(getObjectId())) {
    if (!StringUtil.isEmpty(getUrl())) {
      return directlyCreate(paramData);
    }
    logger.d("createToken params: " + paramData.toJSONString() + ", " + this);
    StorageClient storageClient = PaasClient.getStorageClient();
    Observable<AVFile> result = storageClient.newUploadToken(paramData)
            .map(new Function<FileUploadToken, AVFile>() {
              public AVFile apply(@NonNull FileUploadToken fileUploadToken) throws Exception {
                logger.d("[Thread:" + Thread.currentThread().getId() + "]" + fileUploadToken.toString() + ", " + AVFile.this);
                AVFile.this.setObjectId(fileUploadToken.getObjectId());
                AVFile.this.internalPutDirectly(KEY_OBJECT_ID, fileUploadToken.getObjectId());
                AVFile.this.internalPutDirectly(KEY_BUCKET, fileUploadToken.getBucket());
                AVFile.this.internalPutDirectly(KEY_PROVIDER, fileUploadToken.getProvider());
                AVFile.this.internalPutDirectly(KEY_FILE_KEY, fileKey);

                Uploader uploader = new FileUploader(AVFile.this, fileUploadToken, callback);
                AVFile.this.internalPutDirectly(KEY_URL, fileUploadToken.getUrl());

                AVException exception = uploader.execute();

                JSONObject completeResult = new JSONObject();
                completeResult.put("result", null == exception);
                completeResult.put("token",fileUploadToken.getToken());
                logger.d("file upload result: " + completeResult.toJSONString());
                try {
                  PaasClient.getStorageClient().fileCallback(completeResult);
                  if (null != exception) {
                    logger.w("failed to invoke fileCallback. cause:", exception);
                    throw exception;
                  } else {
                    return AVFile.this;
                  }
                } catch (IOException ex) {
                  logger.w(ex);
                  throw ex;
                }
              }
            });
    result = storageClient.wrapObservable(result);
    return result;
  } else {
    logger.d("file has been upload to cloud, ignore update request.");
    return Observable.just(this);
  }
}