类com.alibaba.fastjson.JSONPath源码实例Demo

下面列出了怎么用com.alibaba.fastjson.JSONPath的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: JustAuth   文件: JsonPathTest.java
@Test
public void jsonPath() {
    List<Map<String, Map<String, Object>>> list = new ArrayList<>();

    Map<String, Map<String, Object>> map = new HashMap<>();
    Map<String, Object> node = new HashMap<>();
    node.put("emailAddress", "xxxx");
    map.put("handle~", node);
    list.add(map);


    Map<String, Object> master = new HashMap<>();
    master.put("elements", list);
    JSONObject emailObj = JSONObject.parseObject(JSON.toJSONString(master));
    Object object = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
    Assert.assertEquals("xxxx", object);
}
 
源代码2 项目: tieba-api   文件: TieBaApi.java
/**
 * 获取关注列表
 * @param bduss bduss
 * @param pn 页码
 * @param fList 关注合集
 */
@SuppressWarnings("unchecked")
private void getFollowList(String bduss, Integer pn, List<Map<String,Object>> fList){
	List<NameValuePair> list = new ArrayList<NameValuePair>();
	list.add(new BasicNameValuePair("BDUSS", bduss));
	list.add(new BasicNameValuePair("_client_id", "wappc_1542694366490_105"));
	list.add(new BasicNameValuePair("_client_type", "2"));
	list.add(new BasicNameValuePair("_client_version", "9.8.8.13"));
	list.add(new BasicNameValuePair("pn", pn + ""));
	list.add(new BasicNameValuePair("timestamp", System.currentTimeMillis()+""));
	list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
	try {
		HttpResponse response = hk.execute(Constants.GET_FOLLOW_LIST, null, list);
		String result = EntityUtils.toString(response.getEntity());
		fList.addAll((List<Map<String, Object>>) JSONPath.eval(JSON.parse(result), "follow_list"));
		String hasMore = JsonKit.getInfo("has_more", result).toString();
		if(hasMore.equals("1")) {
			//还有下一页
			pn++;
			this.getFollowList(bduss, pn, fList);
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
}
 
源代码3 项目: tieba-api   文件: TieBaApi.java
/**
 * 获取粉丝列表
 * @param bduss bduss
 * @param pn 页码
 * @param fList 粉丝集合
 */
@SuppressWarnings("unchecked")
private void getFansList(String bduss, Integer pn, List<Map<String,Object>> fList){
	List<NameValuePair> list = new ArrayList<NameValuePair>();
	list.add(new BasicNameValuePair("BDUSS", bduss));
	list.add(new BasicNameValuePair("_client_id", "wappc_1542694366490_105"));
	list.add(new BasicNameValuePair("_client_type", "2"));
	list.add(new BasicNameValuePair("_client_version", "9.8.8.13"));
	list.add(new BasicNameValuePair("pn", pn + ""));
	list.add(new BasicNameValuePair("timestamp", System.currentTimeMillis()+""));
	list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
	try {
		HttpResponse response = hk.execute(Constants.GET_FANS_LIST, null, list);
		String result = EntityUtils.toString(response.getEntity());
		fList.addAll((List<Map<String, Object>>) JSONPath.eval(JSON.parse(result), "user_list"));
		String hasMore = (String) JSONPath.eval(JSON.parse(result), "$.page.has_more");
		if(hasMore.equals("1")) {
			//还有下一页
			pn++;
			this.getFansList(bduss, pn, fList);
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
}
 
源代码4 项目: tieba-api   文件: TieBaApi.java
/**
 * 查询是否关注某个贴吧
 * @param tbName 贴吧名称
 * @param bduss bduss
 * @return true or false
 */
public Boolean isFocus(String tbName, String bduss) {
	HttpKit hk = HttpKit.getInstance();
	Boolean flag = false;
	try {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("fid", api.getFid(tbName)));
		list.add(new BasicNameValuePair("kw", tbName));
		list.add(new BasicNameValuePair("tbs", api.getTbs(bduss)));
		list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
		HttpResponse response = hk.execute(Constants.LIKE_TIEBA_URL, null, list);
		String fr = EntityUtils.toString(response.getEntity());
		Integer isLike = (Integer)JSONPath.eval(JSON.parse(fr), "$.info.is_like");
		if(isLike == 1) {
			flag = true;
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	if(flag == false) {
		//查询结果后如果未关注,需要取消关注
		this.unfocus(bduss, tbName);
	}
	return flag;
}
 
源代码5 项目: tieba-api   文件: TieBaApi.java
/**
 * 名人堂助攻
 * @param bduss bduss
 * @param tbName 贴吧名称
 * @param tbs tbs
 * @return 结果
 * no=210009 //不在名人堂
 * no=3110004 //暂未关注
 * no=2280006 //已助攻
 * no=0 //成功
 */
public String support(String bduss, String tbName, String tbs) {
	String suportResult = "";
	try {
		HttpResponse hp = hk.execute(String.format(Constants.TIEBA_URL_HTTPS, tbName));
		if(hp == null) {
			hp = hk.execute(String.format(Constants.TIEBA_URL_HTTP, tbName));
		}
		String fidHtml= EntityUtils.toString(hp.getEntity());
		String fid = StrKit.substring(fidHtml, "forum_id\":", ",");
		String cookie = createCookie(bduss);
		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("forum_id", fid));
		params.add(new BasicNameValuePair("tbs", tbs));
		//3.获取npc_id
		String result = EntityUtils.toString(hk.execute(Constants.GET_FORUM_SUPPORT, cookie, params).getEntity());
		String npcId = JSONPath.eval(JSON.parse(result), "$.data[0].npc_info.npc_id").toString();
		params.add(new BasicNameValuePair("npc_id", npcId));
		//3.助攻
		suportResult = EntityUtils.toString(hk.execute(Constants.FORUM_SUPPORT,cookie, params).getEntity());
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	return suportResult;
}
 
源代码6 项目: JustAuth   文件: AuthLinkedinRequest.java
/**
 * 获取用户的email
 *
 * @param accessToken 用户授权后返回的token
 * @return 用户的邮箱地址
 */
private String getUserEmail(String accessToken) {
    HttpHeader httpHeader = new HttpHeader();
    httpHeader.add("Host", "api.linkedin.com");
    httpHeader.add("Connection", "Keep-Alive");
    httpHeader.add("Authorization", "Bearer " + accessToken);

    String emailResponse = new HttpUtils(config.getHttpConfig()).get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))", null, httpHeader, false);
    JSONObject emailObj = JSONObject.parseObject(emailResponse);

    this.checkResponse(emailObj);

    Object obj = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
    return null == obj ? null : (String) obj;
}
 
源代码7 项目: tieba-api   文件: TieBaApi.java
/**
 * 举报帖子
 * @param bduss bduss
 * @param pid 帖子id
 * @param jubaotype 举报类型
 * 10001 低俗色情
 * 10002 垃圾广告
 * 10002 内容低俗无意义
 * 10004 辱骂攻击
 * 10005 其他违法信息
 * 20001 抄袭我的内容
 * 20002 暴露我的隐私
 * 20003 内容里有关我的不实描述
 * @param reason 举报原因
 * @return 举报结果{"errno":21,"msg":"您已举报过该贴,我们将于24小时内通过系统消息发送处理结果。"},{"errno":0,"msg":"举报成功,我们将于24小时内通过系统消息发送处理结果。"}
 */
public String jubao(String bduss, String pid, String jubaotype, String reason){
	try {
		HttpResponse response = hk.execute(String.format(Constants.TOOUSU_CHECK, pid), createCookie(bduss));
		String result = EntityUtils.toString(response.getEntity());
		String url = (String)JSONPath.eval(JSON.parse(result), "$.data.url");
		if(StrKit.isBlank(url)) {
			return "{\"errno\":21,\"msg\":\"您已举报过该贴,我们将于24小时内通过系统消息发送处理结果。\"}";
		}
		url = url.replaceAll("&amp;", "&");
		HttpResponse rep2 = hk.execute(url, createCookie(bduss));
		String add = EntityUtils.toString(rep2.getEntity());
		Document doc = Jsoup.parse(add);
		String category  = doc.getElementById("category").val();
		String product_id  = doc.getElementById("product_id").val();
		String client  = doc.getElementById("client").val();
		String submit_token  = doc.getElementById("submit_token").val();
		String sign  = doc.getElementById("sign").val();
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("product_id", product_id));
		list.add(new BasicNameValuePair("client", client));
		list.add(new BasicNameValuePair("category", category));
		list.add(new BasicNameValuePair("submit_token", submit_token));
		list.add(new BasicNameValuePair("sign", sign));
		list.add(new BasicNameValuePair("jubaotype",jubaotype));
		list.add(new BasicNameValuePair("reason",reason));
		list.add(new BasicNameValuePair("pid",pid));
		String submit_r =  EntityUtils.toString(hk.execute(Constants.TOOUSU_SUBMIT,  createCookie(bduss), list).getEntity());
		Integer code = (Integer)JsonKit.getInfo("errno", submit_r);
		if(code == 0) {
			return "{\"errno\":0,\"msg\":\"举报成功,我们将于24小时内通过系统消息发送处理结果。\"}";
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	return "";
}
 
源代码8 项目: tieba-api   文件: TieBaApi.java
/**
 * 根据百度盘分享url查询完整用户名(大部分可查)
 * @param panUrl 百度云盘分享url
 * @return 完整用户名
 */
public String getFullNameByPanUrl(String panUrl) {
	try {
		panUrl = StrUtil.replace(panUrl, "wap", "share");
		String html = EntityUtils.toString(hk.execute(panUrl).getEntity());
		String uk = StrKit.substring(html, "uk\":", ",");
		String json = HttpUtil.get(String.format(Constants.UK_UN, uk));
		JSONObject jsonObject = JSON.parseObject(json);
		String un = JSONPath.eval(jsonObject, "$.user_info.uname").toString();
		return un;
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	return null;
}
 
源代码9 项目: MicroCommunity   文件: RuleCommon.java
/**
 * 通过jpath 获取值
 * @param jPath
 * @param reqJson
 * @return
 */
private String getNodeValueFromJson(String jPath,String reqJson){
    String nodeValue = "";
    JSONObject reqJsonObject = null;
    if (!StringUtils.isEmpty(reqJson)) {
        try {
            reqJsonObject = JSONObject.parseObject(reqJson);
        } catch (Exception e) {
            return "给出的报文格式存在错误,无法转换为JSON对象,具体原因为:" + e;
        }
        //报文中SOO对象的根节点
        if (null != reqJsonObject) {
            if (null != jPath && !"".equals(jPath)) {
                String[] array1 = jPath.split(RuleDomain.RULE_SIGN_9);
                int length1 = array1.length;
                if (0 < length1) {
                    String sooNodeJpathTmp = null;
                    for (int i = 0; i < length1; i++) {
                        sooNodeJpathTmp = array1[i];
                        if (null != sooNodeJpathTmp && !"".equals(sooNodeJpathTmp)) {
                            if(!sooNodeJpathTmp.startsWith("$.")){
                                sooNodeJpathTmp = "$."+sooNodeJpathTmp;
                            }
                            Object valueObj = JSONPath.eval(reqJsonObject,sooNodeJpathTmp);
                            if (null != valueObj && valueObj instanceof String) {
                                nodeValue = nodeValue + ",'" +valueObj + "'";
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    return nodeValue.length()>0?nodeValue.substring(1):"";
}
 
源代码10 项目: pragmatic-java-engineer   文件: FastJsonExample.java
public static void main(String[] args) {
    User user = new User();
    user.setName("testUser");
    user.setGender("M");
    user.setNickName("nickTest");

    SerializeConfig config = new SerializeConfig();
    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    String str = JSON.toJSONString(user, config);
    System.out.println(str);

    user = JSON.parseObject(str, User.class);

    JSONObject jo = JSON.parseObject("{\"name\":\"test\"}");
    String name = jo.getString("name");
    String nick = jo.getString("nickName");

    System.out.println(nick);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", "test");

    String jsonStr = "{\"name\":\"testName\",\"interests\":[\"music\",\"basketball\"]," +
            "\"notes\":[{\"title\":\"note1\",\"contentLength\":200},{\"title\":\"note2\",\"contentLength\":100}]}";
    JSONObject jsonObject1 = JSON.parseObject(jsonStr);
    System.out.println(JSONPath.eval(jsonObject1, "$.interests.size()"));
    System.out.println(JSONPath.eval(jsonObject1, "$.interests[0]"));
    System.out.println(JSONPath.eval(jsonObject1, "$.notes[contentLength > 100].title"));
    System.out.println(JSONPath.eval(jsonObject1, "$.notes['title']"));
}
 
源代码11 项目: DDMQ   文件: CommonFastJsonUtils.java
@Override
public JSONPath load(String path) {
    LOGGER.info("create jsonPath object for {}", path);
    return JSONPath.compile(path);
}
 
源代码12 项目: DDMQ   文件: JsonUtils.java
@Override
public JSONPath load(String path) {
    LOGGER.info("create jsonPath object for {}", path);
    return JSONPath.compile(path);
}
 
源代码13 项目: DDMQ   文件: CommonFastJsonUtils.java
@Override
public JSONPath load(String path) {
    LOGGER.info("create jsonPath object for {}", path);
    return JSONPath.compile(path);
}
 
源代码14 项目: DDMQ   文件: JsonUtils.java
@Override
public JSONPath load(String path) {
    LOGGER.info("create jsonPath object for {}", path);
    return JSONPath.compile(path);
}
 
源代码15 项目: MicroCommunity   文件: CustIdTest.java
public void testCustId(){
    String jsonStr = " { \"actionTypeCd\": \"C1\", \"boCust\": [ " +
            "{ \"custId\": \"123\", \"name\": \"S\", \"email\": \"-52\", \"cellphone\": \"17797173942\", \"realName\": \"wuxw\", \"sex\": \"1\", \"password\": \"123456\", \"lanId\": \"863010\", \"custAdress\": \"青海省西宁市城中区格兰小镇\", \"custType\": \"1\", \"openId\": \"\", \"state\": \"ADD\" }, { \"custId\": \"-1\", \"name\": \"S\", \"email\": \"-52\", \"cellphone\": \"17797173942\", \"realName\": \"wuxw\", \"sex\": \"1\", \"password\": \"123456\", \"lanId\": \"863010\", \"custAdress\": \"青海省西宁市城中区格兰小镇\", \"custType\": \"1\", \"openId\": \"\", \"state\": \"DEL\" } ], \"boCustAttr\": [ { \"custId\": \"123\", \"prodId\": \"-1\", \"attrCd\": \"123344\", \"value\": \"1\", \"state\": \"ADD\" }, { \"custId\": \"123\", \"prodId\": \"-1\", \"attrCd\": \"123345\", \"value\": \"1\", \"state\": \"DEL\" } ] } ";
    JSONObject custInfo = JSONObject.parseObject(jsonStr);
    System.out.println(JSONPath.eval(custInfo,"$.boCust[custId < '0'][0].custId"));
}
 
源代码16 项目: MicroCommunity   文件: JsonPathTest.java
@Test
public void testObj() throws Exception {
    String  req = "{\n" +
            "    \"ContractRoot\": {\n" +
            "        \"SvcCont\": {\n" +
            "\t \"CustOrderInfo\": {\n" +
            "                \"CustId\": \"713005098855\",\n" +
            "                \"StaffCode\": \"QH1001\",\n" +
            "                \"ChannelNbr\": \"6301041000000\",\n" +
            "                \"RegionCode\": \"8630101\",\n" +
            "                \"OrderId\": \"No Requsted\",\n" +
            "\"AttrInfos\":[\n" +
            "{\n" +
            "\"AttrSpecId\":\"40020005\",\n" +
            "\"AttrValue\":\"\",\n" +
            "\"AttrType\":\"1\"\n" +
            "},\n" +
            "{\n" +
            "\"AttrSpecId\":\"40020006\",\n" +
            "\"AttrValue\":\"\",\n" +
            "\"AttrType\":\"1\"\n" +
            "},\n" +
            "{\n" +
            "\"AttrSpecId\":\"40020007\",\n" +
            "\"AttrValue\":\"\",\n" +
            "\"AttrType\":\"1\"\n" +
            "}\n" +
            "]\n" +
            "            },\n" +
            "            \"ProdOfferInfo\": [\n" +
            "                {\n" +
            "                    \"ProdOfferNbr\": \"800009346\",\n" +
            "                    \"ProdOfferInstId\": \"-1\",\n" +
            "                    \"Action\": \"ADD\",\n" +
            "\"startDt\":\"20170426094245\",\n" +
            "\"endDt\":\"30000000000000\",\n" +
            "                    \"AttrInfos\": [{\n" +
            "\"AttrSpecId\":\"800009346\",\n" +
            "\"AttrValue\":\"800009346\"\n" +
            "}],\n" +
            "                    \"OfferProdRelInfo\": [\n" +
            "                        {\n" +
            "                            \"ProdInstId\": \"713030122316\",\n" +
            "                            \"RoleCd\": \"7006\"\n" +
            "                        }\n" +
            "                    ]\n" +
            "                }\n" +
            "            ]  \n" +
            "        },\n" +
            "        \"TcpCont\": {\n" +
            "            \"AppKey\": \"1001000102\",\n" +
            "            \"DstSysID\": \"6004050001\",\n" +
            "            \"Method\": \"order.offer.addprodoffer\",\n" +
            "            \"Sign\": \"123\",\n" +
            "            \"Version\": \"1.0\",\n" +
            "            \"TransactionID\": \"6001000102201703250000014160\",\n" +
            "            \"ReqTime\": \"20170325115245788\"\n" +
            "        }\n" +
            "    }\n" +
            "}";

    Object obj = JSONPath.eval(JSONObject.parseObject(req),"$.ContractRoot.SvcCont.ProdOfferInfo.AttrInfos[AttrSpecId not in ('40020005','40020006','40020007')]");
    System.out.println(obj.toString());
}
 
源代码17 项目: DBus   文件: FlattenJsonArrayRule.java
private static List<String> flattenJsonArray(String wkVal, String path) {
    List<String> rows = new ArrayList<>();
    JSONObject json = JSONObject.parseObject(wkVal);
    String parentPath = StringUtils.substringBeforeLast(path, ".");
    String currentPath = StringUtils.substringAfterLast(path, ".");
    if (json.containsKey(path)) {
        parentPath = StringUtils.EMPTY;
        currentPath = path;
    }
    Object currentJsonObj = JSONPath.read(wkVal, path);
    Object parentJsonObj = null;
    if (StringUtils.isBlank(parentPath)) {
        parentJsonObj = json;
    } else {
        parentJsonObj = JSONPath.read(wkVal, parentPath);
    }

    if (currentJsonObj instanceof JSONArray) {
        JSONArray retJsonArray = new JSONArray();
        JSONArray currentJsonArray = (JSONArray) currentJsonObj;
        for (int i = 0; i < currentJsonArray.size(); i++) {
            JSONObject jsonItemWk = new JSONObject();
            if (parentJsonObj instanceof JSONObject) {
                jsonItemWk = JSONObject.parseObject(((JSONObject) parentJsonObj).toJSONString());
                jsonItemWk.remove(currentPath);
            }
            jsonItemWk.put(currentPath, currentJsonArray.get(i));
            retJsonArray.add(jsonItemWk);
        }
        if (json.containsKey(path)) {
            for (int i = 0; i < retJsonArray.size(); i++) {
                JSONObject item = (JSONObject) retJsonArray.get(i);
                rows.add(item.toJSONString());
            }
        } else {
            JSONPath.set(json, parentPath, retJsonArray);
            rows.add(json.toJSONString());
        }
    }
    return rows;
}
 
源代码18 项目: vscrawler   文件: AbstractSelectable.java
public AbstractSelectable jsonPath(String jsonPathStr) {
    // FastJson 内部会缓存1024个规则,所以本身应该也会有缓存,对于JsonPath的规则缓存问题,可以先不用考虑了
    return jsonPath(JSONPath.compile(jsonPathStr));
}
 
 类所在包
 类方法
 同包方法