优雅获取json中某个字段

项目中需要获取Json某个字段名称

譬如:获取改Json中orderNo字段的值
{
 "sign":"f/gRYw0q0LjtcqAfEGLu/nyAiKRNRdFSA323SG4ZdnTvhnwxAjpSt+49AwJRc9gG81KveSr09D5/7dYIt0N4TLLR396wwc1+XLiXviH4MlExOawnAxmC4x5D2n1tnDorsU1GhakS/W1pxYU29LHwDXpzReZ+Pa3bBwxSs2Ob0c4=",
 "body":{
  "proposalNo":"T211517002266000090",
  "areaCode":"150700000000",
  "orderNo":"1453599404018298882",
  "premium":"13.54",
  "resultMess":"审核通过",
  "resultCode":"1",
  "riskCode":"MG"
 }
}
传统获取方式
        String orderNo = "";
        JSONObject jsonObj = JSON.parseObject(result);
        if (jsonObj != null) {
            JSONObject obj = jsonObj.getJSONObject("body");
            if (obj != null) {
                orderNo = obj.getString("orderNo");
            }
        }
使用java8 获取
 JSONObject jsonObj = JSON.parseObject(result);

        // 报文获取订单号
        String orderNo = Optional.ofNullable(jsonObj)
                .flatMap(jsonObject -> Optional.ofNullable(jsonObject.getJSONObject("body")))
                .flatMap(jsonObject -> Optional.ofNullable(jsonObject.getString("orderNo")))
                .orElse(null);

完整代码如下
@Around("pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        HttpServletRequest httpServletRequest = getHttpServletRequest();
        final String mchNo = httpServletRequest.getHeader("mchNo");

        final String str = JSONObject.toJSONString(proceedingJoinPoint.getArgs());
        String result = StringUtils.removeEnd(StringUtils.removeStart(str, "["), "]");
        JSONObject jsonObj = JSON.parseObject(result);

        // 报文获取订单号
        String orderNo = Optional.ofNullable(jsonObj)
                .flatMap(jsonObject -> Optional.ofNullable(jsonObject.getJSONObject("body")))
                .flatMap(jsonObject -> Optional.ofNullable(jsonObject.getString("orderNo")))
                .orElse(null);

        if (StringUtils.isEmpty(mchNo)) {
            return buildResponse(ApiCodeEnum.mchNo商户号不能为空, "mchNo商户号不能为空", orderNo);
        }

        InsuranceMchQuery query = new InsuranceMchQuery();
        query.setMchNo(mchNo);
        final InsuranceMchVO oneEnhance = insuranceMchService.getOneEnhance(query);

        if (oneEnhance == null) {
            log.debug("【商户号校验】 工保网未配置商户号 订单号:{} ", orderNo);
            return buildResponse(ApiCodeEnum.商户号未授权, "商户未授权", orderNo);
        }

        // 放入缓存
        UnifiedConfigKit.setThreadLocalMch(oneEnhance);

        Object proceed = proceedingJoinPoint.proceed();
        // 删除缓存
        UnifiedConfigKit.removeThreadLocalMch();

        return proceed;
    }

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值