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

The following examples show how to use com.alibaba.fastjson.JSONObject#parseObject() . These examples are extracted from open source projects. 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 Project: JustAuth   File: AuthQqRequest.java    License: MIT License 6 votes vote down vote up
/**
 * 获取QQ用户的OpenId,支持自定义是否启用查询unionid的功能,如果启用查询unionid的功能,
 * 那就需要开发者先通过邮件申请unionid功能,参考链接 {@see http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D}
 *
 * @param authToken 通过{@link AuthQqRequest#getAccessToken(AuthCallback)}获取到的{@code authToken}
 * @return openId
 */
private String getOpenId(AuthToken authToken) {
    String response = new HttpUtils(config.getHttpConfig()).get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me")
        .queryParam("access_token", authToken.getAccessToken())
        .queryParam("unionid", config.isUnionId() ? 1 : 0)
        .build());
    String removePrefix = response.replace("callback(", "");
    String removeSuffix = removePrefix.replace(");", "");
    String openId = removeSuffix.trim();
    JSONObject object = JSONObject.parseObject(openId);
    if (object.containsKey("error")) {
        throw new AuthException(object.get("error") + ":" + object.get("error_description"));
    }
    authToken.setOpenId(object.getString("openid"));
    if (object.containsKey("unionid")) {
        authToken.setUnionId(object.getString("unionid"));
    }
    return StringUtils.isEmpty(authToken.getUnionId()) ? authToken.getOpenId() : authToken.getUnionId();
}
 
Example 2
/**
 * 查询 所有省市
 *
 * @param pd
 * @return
 */
@Override
public ResponseEntity<String> getAreas(IPageData pd) {
    ResponseEntity<String> responseEntity = null;
    Assert.hasLength(pd.getUserId(), "用户还未登录请先登录");
    JSONObject param = JSONObject.parseObject(pd.getReqData());

    responseEntity = this.callCenterService(restTemplate, pd, "", ServiceConstant.SERVICE_API_URL + "/api/area.listAreas" + mapToUrlParam(param), HttpMethod.GET);

    if (responseEntity.getStatusCode() == HttpStatus.OK) {
        Assert.jsonObjectHaveKey(responseEntity.getBody(), "areas", "查询中心服务异常,不是有效json或未包含areas节点");
        //将areas 返回出去
        responseEntity = new ResponseEntity<String>(JSONObject.parseObject(responseEntity.getBody()).getJSONArray("areas").toJSONString(), HttpStatus.OK);
    }
    return responseEntity;
}
 
Example 3
Source Project: JustAuth   File: AuthMeituanRequest.java    License: MIT License 6 votes vote down vote up
@Override
public AuthResponse refresh(AuthToken oldToken) {
    Map<String, String> form = new HashMap<>(4);
    form.put("app_id", config.getClientId());
    form.put("secret", config.getClientSecret());
    form.put("refresh_token", oldToken.getRefreshToken());
    form.put("grant_type", "refresh_token");

    String response = new HttpUtils(config.getHttpConfig()).post(source.refresh(), form, false);
    JSONObject object = JSONObject.parseObject(response);

    this.checkResponse(object);

    return AuthResponse.builder()
        .code(AuthResponseStatus.SUCCESS.getCode())
        .data(AuthToken.builder()
            .accessToken(object.getString("access_token"))
            .refreshToken(object.getString("refresh_token"))
            .expireIn(object.getIntValue("expires_in"))
            .build())
        .build();
}
 
Example 4
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {
        String contract = request.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));
        Util.checkBodySize(contract);
        boolean visible = Util.getVisiblePost(contract);
        ProposalDeleteContract.Builder build = ProposalDeleteContract.newBuilder();
        JsonFormat.merge(contract, build, visible);
        Transaction tx = wallet
                .createTransactionWrapper(build.build(), ContractType.ProposalDeleteContract)
                .getInstance();
        JSONObject jsonObject = JSONObject.parseObject(contract);
        tx = Util.setTransactionPermissionId(jsonObject, tx);
        response.getWriter().println(Util.printCreateTransaction(tx, visible));
    } catch (Exception e) {
        logger.debug("Exception: {}", e.getMessage());
        try {
            response.getWriter().println(Util.printErrorMsg(e));
        } catch (IOException ioe) {
            logger.debug("IOException: {}", ioe.getMessage());
        }
    }
}
 
Example 5
Source Project: actframework   File: PojoBindingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapPojoBinding() throws Exception {
    url("/pojo/fooMap").get(
            "fooMap.x.id", "abc",
            "fooMap.x.bar.id", "xyz",
            "fooMap.y.id", "a123",
            "fooMap.y.bar.id", "a000"
    );
    String body = resp().body().string();
    JSONObject json = JSONObject.parseObject(body);
    Foo x = json.getObject("x", Foo.class);
    eq("abc", x.getId());
    eq("xyz", x.getBar().getId());
    Foo y = json.getObject("y", Foo.class);
    eq("a000", y.getBar().getId());
}
 
Example 6
Source Project: kafka-monitor   File: JsonLoader.java    License: Apache License 2.0 6 votes vote down vote up
public static JSONObject loadJSONFile(InputStream inputStream) {

        JSONObject confJSONObj;
        try {
            byte[] buf = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while (inputStream.available() > 0) {
                int readSize = inputStream.read(buf, 0, buf.length);
                if (readSize > 0) {
                    baos.write(buf, 0, readSize);
                }
            }
            if (baos.size() > 0) {
                confJSONObj = JSONObject.parseObject(baos.toString("UTF-8"));
            } else {
                confJSONObj = JSONObject.parseObject("{}");
            }
        } catch (Exception e) {
            logger.error(" load JSON file err {} ", e);
            confJSONObj = JSONObject.parseObject("{}");
        }
        return confJSONObj;
    }
 
Example 7
/**
 * 保存耗时信息
 *
 * @param businessServiceDataFlow
 */
private void saveCostTimeLogMessage(BusinessServiceDataFlow businessServiceDataFlow) {
    try {
        if (MappingConstant.VALUE_ON.equals(MappingCache.getValue(MappingConstant.KEY_COST_TIME_ON_OFF))) {
            List<DataFlowLinksCost> dataFlowLinksCosts = businessServiceDataFlow.getLinksCostDates();
            JSONObject costDate = new JSONObject();
            JSONArray costDates = new JSONArray();
            JSONObject newObj = null;
            for (DataFlowLinksCost dataFlowLinksCost : dataFlowLinksCosts) {
                newObj = JSONObject.parseObject(JSONObject.toJSONString(dataFlowLinksCost));
                newObj.put("dataFlowId", businessServiceDataFlow.getDataFlowId());
                newObj.put("transactionId", businessServiceDataFlow.getTransactionId());
                costDates.add(newObj);
            }
            costDate.put("costDates", costDates);

            KafkaFactory.sendKafkaMessage(KafkaConstant.TOPIC_COST_TIME_LOG_NAME, "", costDate.toJSONString());
        }
    } catch (Exception e) {
        logger.error("报错日志出错了,", e);
    }
}
 
Example 8
private static String content(ProviderType providerType, String templateContent, String templateParams) {
    try {
        if (StringUtils.isNotEmpty(templateParams)) {
            JSONObject param = JSONObject.parseObject(templateParams, Feature.OrderedField);
            return processTemplate(templateContent, providerType.getRegex(), param);
        }
        return "";
    } catch (Exception e) {
        log.error("替换失败", e);
        return "";
    }
}
 
Example 9
Source Project: MicroCommunity   File: EditOrgComponent.java    License: Apache License 2.0 5 votes vote down vote up
public ResponseEntity<String> listEnterCommunitys(IPageData pd) {

        JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
        paramIn.put("auditStatusCd", StateConstant.AGREE_AUDIT);

        IPageData newPd = PageData.newInstance().builder(pd.getUserId(),
                pd.getUserName(), pd.getToken(),
                paramIn.toJSONString(), pd.getComponentCode(),
                pd.getComponentMethod(), "",
                pd.getAppId());

        return communityServiceSMOImpl.listMyCommunity(newPd);

    }
 
Example 10
/**
 * 对请求报文处理
 *
 * @param paramIn
 * @return
 */
private JSONObject refreshParamIn(String paramIn) {
    JSONObject paramObj = JSONObject.parseObject(paramIn);
    paramObj.put("userId", "-1");
    paramObj.put("levelCd", "0");

    return paramObj;
}
 
Example 11
Source Project: supplierShop   File: GenTableServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 设置代码生成其他选项值
 * 
 * @param genTable 设置后的生成对象
 */
public void setTableFromOptions(GenTable genTable)
{
    JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
    if (StringUtils.isNotNull(paramsObj))
    {
        String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
        String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        genTable.setTreeCode(treeCode);
        genTable.setTreeParentCode(treeParentCode);
        genTable.setTreeName(treeName);
    }
}
 
Example 12
/**
 * 校验前台传入房屋信息
 *
 * @param pd 页面数据封装
 */
private void validateSaveRoom(IPageData pd) {

    Assert.jsonObjectHaveKey(pd.getReqData(), "communityId", "请求报文中未包含communityId节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "unitId", "请求报文中未包含unitId节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "roomNum", "请求报文中未包含roomNum节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "layer", "请求报文中未包含layer节点");
    /*Assert.jsonObjectHaveKey(pd.getReqData(), "section", "请求报文中未包含section节点");*/
    Assert.jsonObjectHaveKey(pd.getReqData(), "apartment", "请求报文中未包含apartment节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "builtUpArea", "请求报文中未包含builtUpArea节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "state", "请求报文中未包含state节点");
    /*Assert.jsonObjectHaveKey(pd.getReqData(), "unitPrice", "请求报文中未包含unitPrice节点");*/
    JSONObject reqJson = JSONObject.parseObject(pd.getReqData());

    Assert.hasLength(reqJson.getString("communityId"), "小区ID不能为空");
    Assert.isInteger(reqJson.getString("section"), "房间数不是有效数字");
    Assert.isMoney(reqJson.getString("builtUpArea"), "建筑面积数据格式错误");
    Assert.isMoney(reqJson.getString("unitPrice"), "房屋单价数据格式错误");

   /* if (!"1010".equals(reqJson.getString("apartment")) && !"2020".equals(reqJson.getString("apartment"))) {
        throw new IllegalArgumentException("不是有效房屋户型 传入数据错误");
    }*/

    if (!"2001".equals(reqJson.getString("state"))
            && !"2002".equals(reqJson.getString("state"))
            && !"2003".equals(reqJson.getString("state"))
            && !"2004".equals(reqJson.getString("state"))) {
        throw new IllegalArgumentException("不是有效房屋状态 传入数据错误");
    }

}
 
Example 13
public static String getToken(byte[] policy, byte[] accessKey, byte[] secretKey, String tokenType)
	throws Exception {
	JSONObject policyJson = JSONObject.parseObject(new String(policy));

	// 检查令牌是否符合系统规格
	if (TokenTypeEN.UPLOAD.name().equalsIgnoreCase(tokenType)) {
		UploadPolicy uploadPolicy = JSONObject.toJavaObject(policyJson, UploadPolicy.class);
		if (!UploadPolicy.isValid(uploadPolicy)) {
			throw new Exception("The policy is not conform to the specifications of the system.");
		}
	} else if (TokenTypeEN.DOWNLOAD.name().equalsIgnoreCase(tokenType)) {
		DownloadPolicy downloadPolicy = JSONObject.toJavaObject(policyJson, DownloadPolicy.class);
		if (!DownloadPolicy.isValid(downloadPolicy)) {
			throw new Exception("The policy is not conform to the specifications of the system.");
		}
	} else if (TokenTypeEN.MODIFY.name().equalsIgnoreCase(tokenType)) {
		ModifyPolicy modifyPolicy = JSONObject.toJavaObject(policyJson, ModifyPolicy.class);
		if (!ModifyPolicy.isValid(modifyPolicy)) {
			throw new Exception("The policy is not conform to the specifications of the system.");
		}
	} else {
		throw new Exception("Required token is not supported.");
	}

	// 根据secretKey和policy生成消息摘要(使用基于口令编码的HmacSHA256算法)
	byte[] digest = HmacCoder.encode(policy, secretKey, HmacCoder.HmacTypeEn.HmacSHA512);

	// Token = AccessKey::Digest::Policy。数据拼接之前都要做URL安全的Base64编码
	String token = Base64.encodeBase64URLSafeString(accessKey) + SEPARATOR
		+ Base64.encodeBase64URLSafeString(digest) + SEPARATOR + Base64.encodeBase64URLSafeString(policy);

	return token;
}
 
Example 14
/**
 * 根据taskId 获取 ftp配置信息
 *
 * @return
 */
public String queryFtpItemByTaskId(HttpServletRequest request) {

	// 请求参数为{"taskId":"12"}
	String ftpItemJson = request.getParameter("ftpItemJson");

	if (logger.isDebugEnabled()) {
		logger.debug("---【PrvncFtpToFileSystemConfigAction.queryFtpItemByTaskId】入参为:" + ftpItemJson, ftpItemJson);
	}
	try {

		// 校验格式是否正确
		JSONObject.parseObject(ftpItemJson);
	} catch (Exception e) {
		logger.error("传入参数格式不正确:" + ftpItemJson, e);
		resultMsg = createResultMsg("1999", "传入参数格式不正确:" + ftpItemJson, "");
		return "queryFtpItemByTaskId";
	}

	// 将ftpItemJson装为Map保存操作
	Map paramIn = JSONObject.parseObject(ftpItemJson, Map.class);

	// 根据taskId 查询记录是否存在,如果不存在直接返回失败
	Map ftpItem = iHcFtpFileDAO.queryFtpItemByTaskId(paramIn);
	// 判断是否有对应的数据
	if (ftpItem != null && ftpItem.containsKey("TASKID")) {
		// 更新数据
		this.createResultMsg("0000", "成功", JSONObject.toJSONString(ftpItem));
		return "queryFtpItemByTaskId";
	}
	resultMsg = this.createResultMsg("1999", "删除数据已经不存在,或删除失败", "");

	return "queryFtpItemByTaskId";
}
 
Example 15
/**
 * 获取智能合约输入对象
 *
 * @param cmd
 * @param option
 * @param defaultText 默认文本
 * @return
 */
protected SmartContractPackage.SmartContractInput getSmartContractInput(CommandLine cmd, String option, String
        defaultText) {
    SmartContractPackage.SmartContractInput input = null;

    if (cmd.hasOption(option)) {
        String inputStr = cmd.getOptionValue(option, defaultText);
        log.info("InputStr: " + inputStr);
        JSONObject inputJson = JSONObject.parseObject(inputStr);

        SmartContractPackage.SmartContractInput.Builder inputBuilder =
                SmartContractPackage.SmartContractInput.newBuilder();

        JSONArray argsJSONArray = inputJson.getJSONArray(KEY_ARGS);
        for (int i = 0; i < argsJSONArray.size(); i++) {
            inputBuilder.addArgs(ByteString.copyFrom(argsJSONArray.getString(i).getBytes()));
        }

        input = inputBuilder.build();
        //打印一下参数,检查是否跟预期一致
        for (int i = 0; i < input.getArgsCount(); i++) {
            log.info("Input.getArg: " + input.getArgs(i).toStringUtf8());
        }

        return input;
    }

    return null;
}
 
Example 16
@Override
public ResponseEntity<String>
gateway(IPageData pd) throws Exception {

    JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
    Assert.hasKeyAndValue(paramIn, "fromUserName", "请求报文中未包含fromUserName");
    Assert.hasKeyAndValue(paramIn, "toUserName", "请求报文中未包含toUserName");

    logger.debug("doLogin入参:" + paramIn.toJSONString());
    String responseStr = "";

    String fromUserName = paramIn.getString("fromUserName");
    String toUserName = paramIn.getString("toUserName");
    String keyword = paramIn.getString("keyword");
    String msgType = paramIn.getString("msgType");
    String event = paramIn.getString("event");
    String eventKey = paramIn.getString("eventKey");
    //判断用户是否绑定业主
    boolean bindFlag = judgeBindOwner(pd, fromUserName);
    if (!bindFlag) {
        responseStr = WechatFactory.formatText(toUserName, fromUserName, WechatConstant.NO_BIND_OWNER_RESPONSE_MESSAGE);
        return new ResponseEntity<String>(responseStr, HttpStatus.OK);
    }

    if (WechatConstant.MSG_TYPE_TEXT.equals(msgType)) {
        responseStr = textResponseHandler(fromUserName, toUserName, keyword);
    } else if (WechatConstant.MSG_TYPE_EVENT.equals(msgType)) {
        responseStr = eventResponseHandler(fromUserName, toUserName, keyword, event, eventKey);
    } else {
        responseStr = eventResponseHandler(fromUserName, toUserName, keyword, event, eventKey);
    }
    return new ResponseEntity<>(responseStr, HttpStatus.OK);
}
 
Example 17
/**
 * 小区房屋查询数据校验
 *
 * @param pd 页面数据封装对象
 */
private void validateLoadPropertyConfigFee(IPageData pd) {
    Assert.jsonObjectHaveKey(pd.getReqData(), "communityId", "请求报文中未包含communityId节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "page", "请求报文中未包含page节点");
    Assert.jsonObjectHaveKey(pd.getReqData(), "row", "请求报文中未包含row节点");

    JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
    Assert.hasLength(paramIn.getString("communityId"), "小区ID不能为空");
}
 
Example 18
Source Project: framework   File: ArgsSerializationUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param type
 * @param param
 * @return <br>
 */
public static Object parseObj(final String type, final String param) {
    Object obj = null;
    if (param != null) {
        switch (type) {
            case "byte":
                obj = Byte.parseByte(param);
                break;
            case "short":
                obj = Short.parseShort(param);
                break;
            case "int":
                obj = Integer.parseInt(param);
                break;
            case "long":
                obj = Long.parseLong(param);
                break;
            case "float":
                obj = Float.parseFloat(param);
                break;
            case "double":
                obj = Double.parseDouble(param);
                break;
            case "char":
                obj = param.charAt(0);
                break;
            case "boolean":
                obj = Boolean.parseBoolean(param);
                break;
            case "java.lang.String":
                obj = param;
                break;
            case "java.lang.Integer":
                obj = new Integer(param);
                break;
            default:
                try {
                    obj = JSONObject.parseObject(param, Class.forName(type));
                }
                catch (ClassNotFoundException e) {
                    throw new IllegalArgumentException("输入参数有误", e);
                }
                break;
        }
    }
    return obj;
}
 
Example 19
private JSONObject ConvertToJson(String string) {
    string = string.substring(string.indexOf("(") + 1, string.length());
    string = string.substring(0, string.indexOf(")"));
    JSONObject jsonObject = JSONObject.parseObject(string);
    return jsonObject;
}
 
Example 20
@JsonIgnore
@JSONField(serialize = false, deserialize = false)
public void deserializeFields() {
    this.skillList = JSONObject.parseObject(skillStr, new TypeReference<List<SkillRule>>(){});
}