飞道的博客

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

381人阅读  评论(0)

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);
}

转载:https://blog.csdn.net/u014427391/article/details/108468734
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场