前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java基础系列之fastjson parse多级json数据

Java基础系列之fastjson parse多级json数据

作者头像
SmileNicky
发布2020-10-26 15:45:11
1.1K0
发布2020-10-26 15:45:11
举报
文章被收录于专栏:Nicky's blogNicky's blogNicky's blog

Java基础系列之fastjson parse多级json数据

{
    "success":true,
    "message":"成功",
    "parameters":{
        "data":{
            "userInfo":[
                {
                    "wxUserId":"100289085",
                    "loginId":"admin",
                    "adminLevel":null,
                    "isDelete":false,
                    "departmentId":"1f993833-ef9c-4796-bb58-82176f074049",
                    "mobile":"13590469839",
                    "cardType":null,
                    "sort":"1",
                    "userName":"admin",
                    "userId":"c234c8d1-8eed-11ea-bd4f-00ffc104d3c1",
                    "cardNum":null,
                    "isEnabled":true,
                    "yzyUserId":null,
                    "enLoginId":null,
                    "userType":null,
                    "job":"办公室副主任",
                    "email":null
                }
            ]
        }
    }
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oa.service.OaUserService;
import com.cas.client.util.CasParamKeyEnum;
import com.extra.login.cas.client.util.CasPropertiesLoader;
import com.monitor.controlPanel.util.DateUtil;
import com.common.utils.encrypt.RSAUtils;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.xml.ws.Action;
import java.net.HttpURLConnection;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;


/**
 * <pre>
 *  http调用cas数据工具类
 * </pre>
 *
 * <pre>
 * @author mazq
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/09/03 10:33  修改内容:
 * </pre>
 */
@Component
public class CasInfoApiUtils {

    static Logger LOG = LoggerFactory.getLogger(CasInfoApiUtils.class);

    @Autowired
    OaUserService oaUserService;

    public RestTemplate geTemplate(){
        return new RestTemplate(new HttpsClientRequestFactory());
    }

    public void syncCasUserList(String isAdd) throws Exception {
        final String clientCode = CasPropertiesLoader.getValue(CasParamKeyEnum.APPLICATION_CODE.getCasParamKey()).trim();
        final String publicKey = CasPropertiesLoader.getValue(CasParamKeyEnum.RSA_SECRET_KEY.getCasParamKey()).trim();
        final String apiToken = RSAUtils.encryptByPublicKey(publicKey,clientCode +"-"+System.currentTimeMillis());
        final String syncTime = DateUtil.getStrDate(new Date(System.currentTimeMillis()), DateUtil.DATAFORMAT_yyyy_MM_dd_HH_mm_ss);
        LOG.info("apiToken:{}",apiToken);
        final String serverBasePath = CasPropertiesLoader.getValue(CasParamKeyEnum.APP_SERVER_HOST_URL.getCasParamKey());
        final String url = /*serverBasePath +*/ "http://503df61a3b418d18.natapp.cc:9895"
                +CasPropertiesLoader.getValue(CasParamKeyEnum.USER_LIST_API_URL.getCasParamKey())
                +"?isAdd="+isAdd+"&code="+clientCode+"&syncTime="+ syncTime;
        LOG.info("request url:{}",url);

        HttpHeaders headers = new HttpHeaders();
        headers.set("apiAcount", clientCode);
        headers.set("apiToken", apiToken);
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(null,headers);
        ResponseEntity<String> responseEntity = geTemplate().exchange(url, HttpMethod.GET, requestEntity, String.class);
        LOG.info("statusCode:{},responBody:{}", responseEntity.getStatusCode().value(), responseEntity.getBody());
        if (responseEntity.getStatusCode().value() == 200) {
            String body = responseEntity.getBody();
            JSONObject parameters = JSON.parseObject(body).getJSONObject("parameters");
            JSONObject data =  parameters.getJSONObject("data");
            JSONArray userInfos = data.getJSONArray("userInfo");
            List<Map<String,Object>> casUsers = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < userInfos.size(); i ++) {
                JSONObject userInfo = userInfos.getJSONObject(i);
                String userId = userInfo.getString("userId");
                String cardNum =userInfo.getString("cardNum");
                Map<String,Object> map = new HashMap<String, Object>(2);
                map.put("userId", userId);
                map.put("cardNum", cardNum);
                casUsers.add(map);
            }
        }
    }

   static class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
        @Override
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
            try {
                if (!(connection instanceof HttpsURLConnection)) {// http协议
                    //throw new RuntimeException("An instance of HttpsURLConnection is expected");
                    super.prepareConnection(connection, httpMethod);
                }
                if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
                    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                    // 信任任何链接
                    TrustStrategy anyTrustStrategy = new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                            return true;
                        }
                    };
                    SSLContext ctx = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
                    ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                    super.prepareConnection(httpsConnection, httpMethod);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        // 全量新增数据
        new CasInfoApiUtils().syncCasUserList("0");
    }
}

主要代码,数组列表的用JSONArray ,其余用JsonObject:

String body = responseEntity.getBody();
JSONObject parameters = JSON.parseObject(body).getJSONObject("parameters");
JSONObject data =  parameters.getJSONObject("data");
JSONArray userInfos = data.getJSONArray("userInfo");
List<Map<String,Object>> casUsers = new ArrayList<Map<String, Object>>();
for (int i = 0; i < userInfos.size(); i ++) {
    JSONObject userInfo = userInfos.getJSONObject(i);
    String userId = userInfo.getString("userId");
    String cardNum =userInfo.getString("cardNum");
    Map<String,Object> map = new HashMap<String, Object>(2);
    map.put("userId", userId);
    map.put("cardNum", cardNum);
    casUsers.add(map);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档