Java Code Examples for com.alibaba.fastjson.JSON#toJavaObject()
The following examples show how to use
com.alibaba.fastjson.JSON#toJavaObject() .
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: RedisService.java From SecKillShop with MIT License | 6 votes |
/** * string 字符串转换为指定的对象 * @param str JSON字符串 * @param clazz 指定对象限定名 * @param <T> * @return */ private <T> T stringToBean(String str, Class<T> clazz) { if (str == null || str.length() <= 0 || clazz == null) { return null; } if (clazz == int.class || clazz == Integer.class) { return (T) Integer.valueOf(str); } else if (clazz == String.class) { return (T) str; } else if (clazz == Long.class) { return (T) Long.valueOf(str); } else { return JSON.toJavaObject(JSON.parseObject(str), clazz); } }
Example 2
Source File: JsonImportPlugin.java From xiaoyaoji with GNU General Public License v3.0 | 6 votes |
private void import2x(JSONObject obj,String userId){ Project project = JSON.toJavaObject(obj, Project.class); project.setId(StringUtils.id()); project.setUserId(userId); project.setCreateTime(new Date()); project.setLastUpdateTime(new Date()); ProjectService.instance().createProject(project); ProjectGlobal global = obj.getObject(GLOBAL,ProjectGlobal.class); if(global!=null){ global.setId(StringUtils.id()); global.setProjectId(project.getId()); ServiceFactory.instance().create(global); } importDoc(project.getId(), DEFAULT_PARENT_ID, obj.getJSONArray(EXPORT_KEY_DOCS)); }
Example 3
Source File: DB.java From fastquery with Apache License 2.0 | 6 votes |
static Object select(String sql, Object bean) { Class<?> cls = (bean instanceof Class) ? (Class<?>) bean : bean.getClass(); Connection conn; Statement stat = null; ResultSet rs = null; try { conn = QueryContext.getConn(); stat = conn.createStatement(); LOG.info(sql); QueryContext.addSqls(sql); rs = stat.executeQuery(sql); List<Map<String, Object>> maps = rs2Map(rs); if (maps.isEmpty()) { return null; } return JSON.toJavaObject(new JSONObject(maps.get(0)), cls); } catch (Exception e) { throw new RepositoryException(e); } finally { close(rs, stat); } }
Example 4
Source File: Pub_RedisUtils.java From SuperBoot with MIT License | 6 votes |
/** * 获取用户菜单 * * @param userId 用户ID * @return */ public List getUserMenu(long userId) { ValueOperations<String, String> operations = redisTemplate.opsForValue(); boolean exists = redisTemplate.hasKey(USER_MENU + userId); if (exists) { Object list = operations.get(USER_MENU + userId); if (list instanceof List) { return (List<UserMenuDTO>) list; } Object o = JSON.parse(operations.get(USER_MENU + userId)); List<UserMenuDTO> rList = new ArrayList<>(); List data = JSON.toJavaObject((JSON) o, List.class); for (int i = 0; i < data.size(); i++) { UserMenuDTO item = ((JSONObject) data.get(i)).toJavaObject(UserMenuDTO.class); rList.add(item); } return rList; } return null; }
Example 5
Source File: JsonUtil.java From code with Apache License 2.0 | 5 votes |
/** * 将Json字符串信息转换成对应的Java对象 * * @param json json字符串对象 * @param c 对应的类型 */ public static <T> T parseJsonToObj(String json, Class<T> c) { try { JSONObject jsonObject = JSON.parseObject(json); return JSON.toJavaObject(jsonObject, c); } catch (Exception e) { LOGGER.error(e.getMessage()); } return null; }
Example 6
Source File: PubServiceImpl.java From SuperBoot with MIT License | 5 votes |
@Override public BaseResponse register(RegisterUser registerUser) { if (!isAes()) { //执行数据解密 registerUser.setPlatform(aesDecrypt(registerUser.getPlatform())); registerUser.setVersion(aesDecrypt(registerUser.getVersion())); registerUser.setUserCode(aesDecrypt(registerUser.getUserCode())); registerUser.setUserPassword(aesDecrypt(registerUser.getUserPassword())); registerUser.setUserEmail(aesDecrypt(registerUser.getUserEmail())); registerUser.setUserPhone(aesDecrypt(registerUser.getUserPhone())); registerUser.setUserName(aesDecrypt(registerUser.getUserName())); registerUser.setEndTime(aesDecrypt(registerUser.getEndTime())); } BaseResponse response = userRemote.addUser(registerUser); if (BaseStatus.OK.getCode() == response.getStatus()) { //判断数据状态 if (StatusCode.ADD_SUCCESS.getCode() == response.getCode()) { JSONObject data = (JSONObject) JSON.toJSON(response.getData()); BaseToken bt = JSON.toJavaObject(data, BaseToken.class); //判断白名单,用户是否已经生成过TOKEN了,如果生成过则不再进行登陆操作 String token = getRedisUtils().getTokenAllow(bt.getUserId(), registerUser.getPlatform(), registerUser.getVersion()); if (null == token) { //生成新的TOKEN token = jwtUtils.generateToken(bt); //登陆后将TOKEN信息放入缓存 getRedisUtils().setTokenInfo(token, bt); getRedisUtils().setTokenAllow(bt.getUserId(), registerUser.getPlatform(), registerUser.getVersion(), token); } return new BaseResponse(StatusCode.ADD_SUCCESS, genResToken(bt, token)); } } return response; }
Example 7
Source File: FastJsonProvider.java From JsonSurfer with MIT License | 5 votes |
@Override public <T> T cast(Object value, Class<T> tClass) { if (value instanceof JSON) { return JSON.toJavaObject((JSON) value, tClass); } else { return tClass.cast(value); } }
Example 8
Source File: SessionClient.java From message_interface with MIT License | 5 votes |
/** * 更新用户的轻量CRM资料 * @param fromUid 访客用户的uid * @param crm crm资料,必须是JSONArray格式,内容请参照官网文档 * @return 操作结果 * @throws IOException */ public CommonResult updateCrmInfo(String fromUid, JSONArray crm) throws IOException { JSONObject json = new JSONObject(); json.put(OpenApiTags.UID, fromUid); json.put("userinfo", crm); JSONObject res = send("openapi/event/updateUInfo", json.toJSONString()); return JSON.toJavaObject(res, CommonResult.class); }
Example 9
Source File: CommonParser.java From letv with Apache License 2.0 | 5 votes |
public static <T> T getJsonObj(Class<T> c, JSON content) { try { return JSON.toJavaObject(content, c); } catch (Exception e) { if (e != null) { Logger.d("fornia", "e.getMessage():" + e.getMessage()); } return null; } }
Example 10
Source File: SessionClient.java From message_interface with MIT License | 5 votes |
/** * 如果访客当前正在排队中,可调用此接口查询排队状态 * @param fromUid 消息来源访客的ID * @return 操作结果 * @throws IOException */ public QueryQueueResult getQueueStatus(String fromUid) throws IOException { JSONObject json = new JSONObject(); json.put(OpenApiTags.UID, fromUid); JSONObject res = send("openapi/event/queryQueueStatus", json.toJSONString()); return JSON.toJavaObject(res, QueryQueueResult.class); }
Example 11
Source File: SessionClient.java From message_interface with MIT License | 5 votes |
private CommonResult sendMessage(String fromUid, Object content, String type) throws IOException { QiyuMessage message = new QiyuMessage(); message.setUid(fromUid); message.setContent(content); message.setMsgType(type); JSONObject res = send("openapi/message/send", JSON.toJSONString(message)); return JSON.toJavaObject(res, CommonResult.class); }
Example 12
Source File: JsonUtil.java From springboot-websocket-demo with Apache License 2.0 | 5 votes |
/** * 将Json字符串信息转换成对应的Java对象 * * @param json json字符串对象 * @param c 对应的类型 */ public static <T> T parseJsonToObj(String json, Class<T> c) { try { JSONObject jsonObject = JSON.parseObject(json); return JSON.toJavaObject(jsonObject, c); } catch (Exception e) { LOGGER.error(e.getMessage()); } return null; }
Example 13
Source File: HttpPostRequest.java From gecco with MIT License | 4 votes |
public static HttpPostRequest fromJson(JSONObject request) { return (HttpPostRequest)JSON.toJavaObject(request, HttpPostRequest.class); }
Example 14
Source File: PropertiesUtil.java From fastquery with Apache License 2.0 | 4 votes |
/** * 配置转换 * * @param fqueryResource fquery资源 * @return fastquery.json set结构 */ static Set<FastQueryJson> getFQueryProperties(Resource fqueryResource) { JSONObject json = getFQJSON(fqueryResource); FastQueryJSONObject.setJsonObject(json); FastQueryJSONObject.check(); FastQueryJson[] fqProperties = JSON.toJavaObject(json.getJSONArray("scope"), FastQueryJson[].class); String config; String dataSourceName; Set<String> basePackages; List<String> dataSourceNames = new ArrayList<>(); // 用于存储所有的数据源名称,在fastquery.json文件里禁止dataSourceName重复出现 List<String> bpNames = new ArrayList<>(); // 用于存储所有的basePackage,在fastquery.json文件里禁止basePackage重复出现 Set<FastQueryJson> fqs = new HashSet<>(); for (FastQueryJson fQueryPropertie : fqProperties) { // 顺便校验配置 config = fQueryPropertie.getConfig(); dataSourceName = fQueryPropertie.getDataSourceName(); basePackages = fQueryPropertie.getBasePackages(); if (config == null || "".equals(config)) { throw new RepositoryException("fastquery.json 中的config属性配置错误,提示,不能是空字符且不能为null"); } if ("".equals(dataSourceName)) { throw new RepositoryException("fastquery.json 中的dataSourceName配置错误,提示,不能是空字符且不能为null"); } for (String basePackage : basePackages) { if (basePackage == null || "".equals(basePackage)) { continue; } bpNames.add(basePackage); // 把所有的basePackage收集在一个集合里,方便校验是否有重复 } // 收集数据 用做校验 if (dataSourceName != null) { dataSourceNames.add(dataSourceName); } // 收集数据 用做校验 End fqs.add(fQueryPropertie); } // 校验 fastquery.json check(dataSourceNames, bpNames); return fqs; }
Example 15
Source File: OfficialAccountController.java From message_interface with MIT License | 4 votes |
public static void main(String[] args) { QiyuSessionManager sessionManager = new QiyuSessionManager(); JSONObject json = JSONObject.parseObject("{\"uid\":\"oxWh0uI0j33bSTO_CY9eFxqap9MI\",\"message\":\"哈哈\",\"evaluationModel\":{\"type\":3,\"title\":\"模式二\",\"note\":\"三级评价模式\",\"list\":[{\"value\":100,\"name\":\"满意\"},{\"value\":50,\"name\":\"一般\"},{\"value\":1,\"name\":\"不满意\"}]},\"staffId\":142,\"sessionId\":274491,\"staffName\":\"客服44\",\"staffType\":1,\"staffIcon\":\"http://nos.netease.com/ysf/29C25737ABC2524667D223A90FEF156D\",\"code\":200}"); ApplyStaffResult result = new ApplyStaffResult(); result.setCode(json.getIntValue(OpenApiTags.CODE)); result.setMessage(json.getString(OpenApiTags.MESSAGE)); if (result.getCode() == 200) { result.setSession(JSONObject.toJavaObject(json, Session.class)); } else if (result.getCode() == 14008) { result.setCount(json.getIntValue(OpenApiTags.COUNT)); } sessionManager.onSessionStart(result.getSession()); json = JSONObject.parseObject("{\"uid\":\"oxWh0uI0j33bSTO_CY9eFxqap9MI\",\"message\":\"哈哈\",\"staffId\":142,\"sessionId\":274491,\"staffName\":\"客服44\",\"staffType\":1,\"staffIcon\":\"http://nos.netease.com/ysf/29C25737ABC2524667D223A90FEF156D\",\"code\":200,\"closeReason\":0}"); Session session = JSON.toJavaObject(json, Session.class); sessionManager.onSessionEnd(session); sessionManager.isEvaluationMsg(json.getString("uid"), "1"); String content = "<xml><ToUserName><![CDATA[gh_fbe6f8d3398e]]></ToUserName>\n" + "<FromUserName><![CDATA[oxWh0uI0j33bSTO_CY9eFxqap9MI]]></FromUserName>\n" + "<CreateTime>1477017096</CreateTime>\n" + "<MsgType><![CDATA[image]]></MsgType>\n" + "<PicUrl><![CDATA[http://mmbiz.qpic.cn/mmbiz_jpg/Nt8emaxicaPAXmZSFRePg51tpJd5XNdWt1uDrRCPVfpl3K1nsNzaYcPBmSREOib8cQS155CnOzNvvoYmiatujibWMQ/0]]></PicUrl>\n" + "<MsgId>6343740123371811732</MsgId>\n" + "<MediaId><![CDATA[YMRGXA98VRaHPFCZY69_qKnfFqxVAcJKUlrNSXIS-hGBENaN9gRaqBK_RbG2Tycq]]></MediaId>\n" + "</xml>\n"; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(content); InputSource is = new InputSource(sr); Document document = db.parse(is); final Element root = document.getDocumentElement(); // final String msgType = xmlTextContent(root, "MsgType"); // // String accessToken = new WXAuthService().queryAccessToken(); // CommonResult result = new QiyuSessionService().forwardWxMessage(root, accessToken); // System.out.println(result); } catch (Exception e) { e.printStackTrace(); } }
Example 16
Source File: VSCrawlerCommonUtil.java From vscrawler with Apache License 2.0 | 4 votes |
public static Seed transferStringToSeed(String seed) { return JSON.toJavaObject(JSONObject.parseObject(seed), Seed.class); }
Example 17
Source File: PayChannel4AliServiceImpl.java From xxpay-master with MIT License | 4 votes |
@Override public Map getAliRefundReq(String jsonParam) { String logPrefix = "【支付宝退款查询】"; BaseParam baseParam = JsonUtil.getObjectFromJson(jsonParam, BaseParam.class); Map<String, Object> bizParamMap = baseParam.getBizParamMap(); if (ObjectValidUtil.isInvalid(bizParamMap)) { _log.warn("{}失败, {}. jsonParam={}", logPrefix, RetEnum.RET_PARAM_NOT_FOUND.getMessage(), jsonParam); return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_NOT_FOUND); } JSONObject refundOrderObj = baseParam.isNullValue("refundOrder") ? null : JSONObject.parseObject(bizParamMap.get("refundOrder").toString()); RefundOrder refundOrder = JSON.toJavaObject(refundOrderObj, RefundOrder.class); if (ObjectValidUtil.isInvalid(refundOrder)) { _log.warn("{}失败, {}. jsonParam={}", logPrefix, RetEnum.RET_PARAM_INVALID.getMessage(), jsonParam); return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_INVALID); } String refundOrderId = refundOrder.getRefundOrderId(); String mchId = refundOrder.getMchId(); String channelId = refundOrder.getChannelId(); PayChannel payChannel = baseService4PayOrder.baseSelectPayChannel(mchId, channelId); alipayConfig.init(payChannel.getParam()); AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getApp_id(), alipayConfig.getRsa_private_key(), AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayConfig.getAlipay_public_key(), AlipayConfig.SIGNTYPE); AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest(); AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel(); model.setOutTradeNo(refundOrder.getPayOrderId()); model.setTradeNo(refundOrder.getChannelPayOrderNo()); model.setOutRequestNo(refundOrderId); request.setBizModel(model); Map<String, Object> map = new HashMap<>(); map.put("refundOrderId", refundOrderId); try { AlipayTradeFastpayRefundQueryResponse response = client.execute(request); if(response.isSuccess()){ map.putAll((Map) JSON.toJSON(response)); map.put("isSuccess", true); }else { _log.info("{}返回失败", logPrefix); _log.info("sub_code:{},sub_msg:{}", response.getSubCode(), response.getSubMsg()); map.put("channelErrCode", response.getSubCode()); map.put("channelErrMsg", response.getSubMsg()); } } catch (AlipayApiException e) { _log.error(e, ""); } return RpcUtil.createBizResult(baseParam, map); }
Example 18
Source File: HttpGetRequest.java From gecco with MIT License | 4 votes |
public static HttpGetRequest fromJson(JSONObject request) { return (HttpGetRequest)JSON.toJavaObject(request, HttpGetRequest.class); }
Example 19
Source File: PubServiceImpl.java From SuperBoot with MIT License | 4 votes |
@Override public BaseResponse sso(ReqOtherLogin otherLogin) { if (isAes()) { //执行数据解密 otherLogin.setPlatform(aesDecrypt(otherLogin.getPlatform())); otherLogin.setVersion(aesDecrypt(otherLogin.getVersion())); otherLogin.setUserKey(aesDecrypt(otherLogin.getUserKey())); } //调用用户中心服务获取登陆信息 BaseResponse response = userRemote.sso(otherLogin); if (BaseStatus.OK.getCode() == response.getStatus()) { //判断数据状态 if (StatusCode.OK.getCode() == response.getCode()) { JSONObject data = (JSONObject) JSON.toJSON(response.getData()); BaseToken bt = JSON.toJavaObject(data, BaseToken.class); //判断白名单,用户是否已经生成过TOKEN了,如果生成过则不再进行登陆操作 String token = getRedisUtils().getTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion()); if (null == token) { //生成新的TOKEN token = jwtUtils.generateToken(bt); //登陆后将TOKEN信息放入缓存 getRedisUtils().setTokenInfo(token, bt); getRedisUtils().setTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion(), token); } else { //判断TOKEN是否已经锁定了,如果锁定了则需要重新生成新的TOKEN给客户端 ValueOperations<String, HashMap> operations = getRedisUtils().getRedisTemplate().opsForValue(); boolean exists = getRedisUtils().getRedisTemplate().hasKey(token); if (exists) { HashMap tokenItem = operations.get(token); //如果TOKEN已经锁定,则重新生成TOKEN信息 if (Pub_RedisUtils.TOKEN_STATUS_LOCKED.equals(tokenItem.get(Pub_RedisUtils.TOKEN_STATUS))) { //生成新的TOKEN token = jwtUtils.generateToken(bt); //登陆后将TOKEN信息放入缓存 getRedisUtils().setTokenInfo(token, bt); getRedisUtils().setTokenAllow(bt.getUserId(), otherLogin.getPlatform(), otherLogin.getVersion(), token); } } } return new BaseResponse(genResToken(bt, token)); } } return response; }
Example 20
Source File: PayChannel4AliServiceImpl.java From xxpay-master with MIT License | 4 votes |
/** * 支付宝转账,文档:https://docs.open.alipay.com/api_28/alipay.fund.trans.toaccount.transfer * @param jsonParam * @return */ @Override public Map doAliTransReq(String jsonParam) { String logPrefix = "【支付宝转账】"; BaseParam baseParam = JsonUtil.getObjectFromJson(jsonParam, BaseParam.class); Map<String, Object> bizParamMap = baseParam.getBizParamMap(); if (ObjectValidUtil.isInvalid(bizParamMap)) { _log.warn("{}失败, {}. jsonParam={}", logPrefix, RetEnum.RET_PARAM_NOT_FOUND.getMessage(), jsonParam); return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_NOT_FOUND); } JSONObject transOrderObj = baseParam.isNullValue("transOrder") ? null : JSONObject.parseObject(bizParamMap.get("transOrder").toString()); TransOrder transOrder = JSON.toJavaObject(transOrderObj, TransOrder.class); if (ObjectValidUtil.isInvalid(transOrder)) { _log.warn("{}失败, {}. jsonParam={}", logPrefix, RetEnum.RET_PARAM_INVALID.getMessage(), jsonParam); return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_INVALID); } String transOrderId = transOrder.getTransOrderId(); String mchId = transOrder.getMchId(); String channelId = transOrder.getChannelId(); PayChannel payChannel = baseService4TransOrder.baseSelectPayChannel(mchId, channelId); alipayConfig.init(payChannel.getParam()); AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getApp_id(), alipayConfig.getRsa_private_key(), AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayConfig.getAlipay_public_key(), AlipayConfig.SIGNTYPE); AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest(); AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel(); model.setOutBizNo(transOrderId); model.setPayeeType("ALIPAY_LOGONID"); // 收款方账户类型 model.setPayeeAccount(transOrder.getChannelUser()); // 收款方账户 model.setAmount(AmountUtil.convertCent2Dollar(transOrder.getAmount().toString())); model.setPayerShowName("支付转账"); model.setPayeeRealName(transOrder.getUserName()); model.setRemark(transOrder.getRemarkInfo()); request.setBizModel(model); Map<String, Object> map = new HashMap<>(); map.put("transOrderId", transOrderId); map.put("isSuccess", false); try { AlipayFundTransToaccountTransferResponse response = client.execute(request); if(response.isSuccess()) { map.put("isSuccess", true); map.put("channelOrderNo", response.getOrderId()); }else { //出现业务错误 _log.info("{}返回失败", logPrefix); _log.info("sub_code:{},sub_msg:{}", response.getSubCode(), response.getSubMsg()); map.put("channelErrCode", response.getSubCode()); map.put("channelErrMsg", response.getSubMsg()); } } catch (AlipayApiException e) { _log.error(e, ""); } return RpcUtil.createBizResult(baseParam, map); }