Java Code Examples for cn.hutool.json.JSONUtil#parseObj()

The following examples show how to use cn.hutool.json.JSONUtil#parseObj() . 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: OcrUtils.java    From tools-ocr with GNU Lesser General Public License v3.0 7 votes vote down vote up
private static String extractSogouResult(String html) {
    if (StrUtil.isBlank(html)) {
        return "";
    }
    JSONObject jsonObject = JSONUtil.parseObj(html);
    if (jsonObject.getInt("success", 0) != 1) {
        return "";
    }
    JSONArray jsonArray = jsonObject.getJSONArray("result");
    List<TextBlock> textBlocks = new ArrayList<>();
    boolean isEng;
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jObj = jsonArray.getJSONObject(i);
        TextBlock textBlock = new TextBlock();
        textBlock.setText(jObj.getStr("content").trim());
        //noinspection SuspiciousToArrayCall
        String[] frames = jObj.getJSONArray("frame").toArray(new String[0]);
        textBlock.setTopLeft(CommUtils.frameToPoint(frames[0]));
        textBlock.setTopRight(CommUtils.frameToPoint(frames[1]));
        textBlock.setBottomRight(CommUtils.frameToPoint(frames[2]));
        textBlock.setBottomLeft(CommUtils.frameToPoint(frames[3]));
        textBlocks.add(textBlock);
    }
    isEng = jsonObject.getStr("lang", "zh-Chs").equals("zh-Chs");
    return CommUtils.combineTextBlocks(textBlocks, isEng);
}
 
Example 2
Source File: PictureServiceImpl.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
public void synchronize() {
    //链式构建请求
    String result = HttpRequest.get(CommonConstant.SM_MS_URL + "/v2/upload_history")
            //头信息,多个头信息多次调用此方法即可
            .header("Authorization", token)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    List<Picture> pictures = JSON.parseArray(jsonObject.get("data").toString(), Picture.class);
    for (Picture picture : pictures) {
        if (!pictureDao.existsByUrl(picture.getUrl())) {
            picture.setSize(FileUtils.getSize(Integer.parseInt(picture.getSize())));
            picture.setUsername("System Sync");
            picture.setMd5Code("");
            pictureDao.save(picture);
        }
    }
}
 
Example 3
Source File: PictureServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public void synchronize() {
    //链式构建请求
    String result = HttpRequest.get(YshopConstant.Url.SM_MS_URL + "/v2/upload_history")
            //头信息,多个头信息多次调用此方法即可
            .header("Authorization", token)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    List<Picture> pictures = JSON.parseArray(jsonObject.get("data").toString(), Picture.class);
    for (Picture picture : pictures) {
        if(this.getOne(new QueryWrapper<Picture>().eq("url",picture.getUrl()))==null){
            picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
            picture.setUsername("System Sync");
            picture.setMd5code(null);
            this.save(picture);
        }
    }
}
 
Example 4
Source File: ExComponentRich.java    From PicqBotX with MIT License 6 votes vote down vote up
/**
 * 转换为网页分享富文本组件。
 */
public ExComponentRichNews news()
{
    JSONObject json = JSONUtil.parseObj(content);
    if (json.containsKey("news"))
    {
        JSONObject d = json.getJSONObject("news");
        return new ExComponentRichNews(
                d.getStr("title"),
                d.getStr("desc"),
                d.getStr("preview"),
                d.getStr("tag"),
                d.getStr("jumpUrl")
        );
    }
    else
    {
        throw new UnsupportedOperationException();
    }
}
 
Example 5
Source File: ApiController.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 下载字幕
 */
public void zimu_down() {
	HttpRequest request = getRequest();
	HttpResponse response = getResponse();
	String data = request.getParaToStr("data");
	if(data == null) {
		outJsonpMessage(request,response, 1, "请求数据错误");
		return;
	}
	
	JSONObject dataJson = JSONUtil.parseObj(data);
	JSONArray items = dataJson.getJSONArray("items");
	if(items == null || items.size()==0) {
		outJsonpMessage(request,response, 1, "请选择字幕文件");
		return;
	}
	//System.out.println(data);
	
	DownParm downParm;
	JSONObject row;
	int item_id;
	for(int i = 0; i < items.size(); i++) {
		row = items.getJSONObject(i);
		item_id = row.getInt("id");
		downParm = new DownParm();
		downParm.charset = row.getStr("charset", "");
		downParm.simplified = row.getBool("simplified", false);
		downParm.filenameType = row.getInt("filenameType", 1);

		try {
			DownZIMu.down(item_id, downParm);
		}catch(Exception e) {
			logger.error(e);
		}
		
	}
	outJsonpMessage(request,response, 0, "OK");
}
 
Example 6
Source File: PictureServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Throwable.class)
public Picture upload(MultipartFile multipartFile, String username) {
    File file = FileUtil.toFile(multipartFile);
    // 验证是否重复上传
    Picture picture = pictureRepository.findByMd5Code(FileUtil.getMd5(file));
    if(picture != null){
       return picture;
    }
    HashMap<String, Object> paramMap = new HashMap<>(1);
    paramMap.put("smfile", file);
    // 上传文件
    String result= HttpRequest.post(ElAdminConstant.Url.SM_MS_URL + "/v2/upload")
            .header("Authorization", token)
            .form(paramMap)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    if(!jsonObject.get(CODE).toString().equals(SUCCESS)){
        throw new BadRequestException(TranslatorUtil.translate(jsonObject.get(MSG).toString()));
    }
    picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
    picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
    picture.setUsername(username);
    picture.setMd5Code(FileUtil.getMd5(file));
    picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+"."+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
    pictureRepository.save(picture);
    //删除临时文件
    FileUtil.del(file);
    return picture;

}
 
Example 7
Source File: ApiController.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 查询字幕
 */
public void zimu_list() {
	HttpRequest request = getRequest();
	HttpResponse response = getResponse();
	String data = request.getParaToStr("data");
	if(data == null) {
		outJsonpMessage(request,response, 1, "请求数据错误");
		return;
	}
	
	JSONObject dataJson = JSONUtil.parseObj(data);
	
	
	SearchParm searchParm = new SearchParm();
	searchParm.from_sheshou = dataJson.getJSONObject("searchParm").getBool("from_sheshou");
	searchParm.from_subhd = dataJson.getJSONObject("searchParm").getBool("from_subhd");
	searchParm.from_xunlei = dataJson.getJSONObject("searchParm").getBool("from_xunlei");
	searchParm.from_zimuku = dataJson.getJSONObject("searchParm").getBool("from_zimuku");
	try {
		DownZIMu.searchList(searchParm);
		System.out.println(DownZIMu.dataArr);
	}catch(Exception e) {
		logger.error(e);
		outJsonpMessage(request,response, 1, "查询出错");
		return;
	}
	
	JSONObject resp = new JSONObject();
	resp.put("list", DownZIMu.dataArr);
	outJsonpMessage(request,response, 0, "OK", resp);
}
 
Example 8
Source File: PictureServiceImpl.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Throwable.class)
public Picture upload(MultipartFile multipartFile, String username) {
    File file = FileUtil.toFile(multipartFile);
    // 验证是否重复上传
    Picture picture = this.getOne(new QueryWrapper<Picture>().eq("md5code",FileUtil.getMd5(file)));
    if(picture != null){
        return picture;
    }
    HashMap<String, Object> paramMap = new HashMap<>(1);
    paramMap.put("smfile", file);
    // 上传文件
    String result= HttpRequest.post(YshopConstant.Url.SM_MS_URL + "/v2/upload")
            .header("Authorization", token)
            .form(paramMap)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    if(!jsonObject.get(CODE).toString().equals(SUCCESS)){
        throw new BadRequestException(TranslatorUtil.translate(jsonObject.get(MSG).toString()));
    }
    picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
    picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
    picture.setUsername(username);
    picture.setMd5code(FileUtil.getMd5(file));
    picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+"."+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
    this.save(picture);
    //删除临时文件
    FileUtil.del(file);
    return picture;

}
 
Example 9
Source File: GenUtils.java    From ruoyiplus with MIT License 5 votes vote down vote up
private static void setColumnConfigInfo(ColumnInfo column,Map<String,String[]> params){
    //格式形如:{type:'dict',url:''},type:text(默认),select(下拉框,配合url获取下拉列表),dict(数据词典下拉框),checkbox,radio,date(配合format),autocomplete(配合url),tree(选择树,配合url),switch等
    String _paramValue = Convert.toStr(getParam(params,column.getAttrname() + "_editArg"),"");
    if(!_paramValue.startsWith("{")) _paramValue = "{" + _paramValue;
    if(!_paramValue.endsWith("}")) _paramValue = _paramValue + "}";
    JSONObject json = JSONUtil.parseObj(_paramValue);

    ColumnConfigInfo cci = new ColumnConfigInfo();
    cci.setType(Convert.toStr(json.get("type"),"text"));
    cci.setValue(json.toString());
    cci.setTitle(column.getColumnComment());
    column.setConfigInfo(cci);

}
 
Example 10
Source File: UpgradeCommon.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否有新版
 * @return
 */
public static boolean checkNewVersion() {
	String url = AppConfig.upgradeUrl;
	String str = HtHttpUtil.http.get(url);
	logger.info(str);
	data = JSONUtil.parseObj(str);
	if(data==null) {
		logger.error("未发现新版");
		return false;
	}
	//System.out.println(data);
	return compareVersion(data.getStr("version"), AppConfig.appVer) > 0;
}
 
Example 11
Source File: SubHDCommon.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 下载字幕
 * @param url
 * @return
 */
public static JSONObject downContent(String url) {
	String result = HtHttpUtil.http.get(baseUrl+url, HtHttpUtil.http.default_charset, HtHttpUtil.http._ua, baseUrl+url);
	Document doc = Jsoup.parse(result);
	Elements matchList = doc.select("#down");
	if(matchList.size() == 0)return null;
	Element down = matchList.get(0);
	Map<String, Object> postData = new HashMap<String, Object>();
	postData.put("sub_id", matchList.attr("sid"));
	postData.put("dtoken", down.attr("dtoken"));
	result = HtHttpUtil.http.post(baseUrl+"/ajax/down_ajax", postData);
	if(result == null || !result.contains("}"))return null;
	JSONObject resultJson = JSONUtil.parseObj(result);
	if(resultJson == null || !resultJson.getBool("success"))return null;
	String downUrl = resultJson.getStr("url");
	String filename = StringUtil.basename(downUrl);
	//HtHttpUtil.http.debug=true;
	byte[] data = HtHttpUtil.http.getBytes(downUrl, HtHttpUtil.http._ua, baseUrl+url);
	
	JSONObject resp = new JSONObject();
	resp.put("filename", filename);
	resp.put("ext", StringUtil.extName(filename).toLowerCase());
	resp.put("data", Base64.encode(data));

	
	return resp;
}
 
Example 12
Source File: XunLeiCommon.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
public static JSONArray DownList(String fileName) throws Exception {
	String cid = getCid(fileName);
	String result = HtHttpUtil.http.get(String.format("http://sub.xmp.sandai.net:8000/subxl/%s.json", cid));
	if(result == null) {
		logger.error("未查询到结果");
		return null;
	}
	//System.out.println(result);
	JSONObject json = JSONUtil.parseObj(result);
	return json.getJSONArray("sublist");
}
 
Example 13
Source File: ExtractApiController.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 下载压缩文件中的字幕
 * @param data
 * @return
 */
public void down_archive_file() {
	HttpRequest request = getRequest();
	HttpResponse response = getResponse();
	String data = request.getParaToStr("data");
	if(data == null) {
		outJsonpMessage(request,response, 1, "请求数据错误");
		return;
	}
	logger.info("data="+data);
	if(data == null || data.length() < 10) {
		logger.error("data=null");
		outJsonpMessage(request,response, 1, "参数错误");
		return;
	}
	JSONObject dataJson = JSONUtil.parseObj(data);
	JSONArray items = dataJson.getJSONArray("items");
	if(items == null || items.size() == 0) {
		logger.error("items=null");
		outJsonpMessage(request,response, 1, "参数错误");
		return;
	}
	
	JSONObject resp = new JSONObject();
	resp.put("saveSelected", ExtractDialog.extractDialog.saveSelected(items));
	outJsonpMessage(request,response, 0, "OK", resp);
}
 
Example 14
Source File: XunLeiCommon.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
public static JSONArray DownList(String fileName) throws Exception {
	String cid = getCid(fileName);
	String result = HtHttpUtil.http.get(String.format("http://sub.xmp.sandai.net:8000/subxl/%s.json", cid));
	if(result == null) {
		logger.error("未查询到结果");
		return null;
	}
	//System.out.println(result);
	JSONObject json = JSONUtil.parseObj(result);
	return json.getJSONArray("sublist");
}
 
Example 15
Source File: UploadController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example 16
Source File: ServletUtils.java    From datax-web with MIT License 5 votes vote down vote up
/**
 * 从请求对象中扩展参数数据,格式:JSON 或  param_ 开头的参数
 *
 * @param request 请求对象
 * @return 返回Map对象
 */
public static Map<String, Object> getExtParams(ServletRequest request) {
    Map<String, Object> paramMap = null;
    String params = StrUtil.trim(request.getParameter(DEFAULT_PARAMS_PARAM));
    if (StrUtil.isNotBlank(params) && StrUtil.startWith(params, "{")) {
        paramMap = (Map) JSONUtil.parseObj(params);
    } else {
        paramMap = getParametersStartingWith(ServletUtils.getRequest(), DEFAULT_PARAM_PREFIX_PARAM);
    }
    return paramMap;
}
 
Example 17
Source File: OcrUtils.java    From tools-ocr with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static String extractBdResult(String html) {
    if (StrUtil.isBlank(html)) {
        return "";
    }
    JSONObject jsonObject = JSONUtil.parseObj(html);
    if (jsonObject.getInt("errno", 0) != 0) {
        return "";
    }
    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("words_result");
    List<TextBlock> textBlocks = new ArrayList<>();
    boolean isEng = false;
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jObj = jsonArray.getJSONObject(i);
        TextBlock textBlock = new TextBlock();
        textBlock.setText(jObj.getStr("words").trim());
        //noinspection SuspiciousToArrayCall
        JSONObject location = jObj.getJSONObject("location");
        int top = location.getInt("top");
        int left = location.getInt("left");
        int width = location.getInt("width");
        int height = location.getInt("height");
        textBlock.setTopLeft(new Point(top, left));
        textBlock.setTopRight(new Point(top, left + width));
        textBlock.setBottomLeft(new Point(top + height, left));
        textBlock.setBottomRight(new Point(top + height, left + width));
        textBlocks.add(textBlock);
    }
    return CommUtils.combineTextBlocks(textBlocks, isEng);
}
 
Example 18
Source File: GenServiceImpl.java    From ruoyiplus with MIT License 4 votes vote down vote up
@Override
public byte[] generatorCode(
        TableInfo.GenStyle codeStyle, String tableName, Map<String, String[]> params) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(outputStream);
    // 查询表信息
    String prefix = GenUtils.getParam(params, "prefix");
    TableInfo table = getTableInfo(tableName, prefix, params);
    // 查询列信息
    List<ColumnInfo> columns = table.getColumns();
    // 列的额外信息处理
    for (ColumnInfo c : columns) {
        String[] ss = params.get(c.getAttrname());
        if (ss != null && ss.length == 1) {
            JSONObject _json = JSONUtil.parseObj(ss[0]);
            c.setWidth(Convert.toInt(_json.get("width"), 150));
            c.setVisible(Convert.toBool(_json.get("visible"), true));
            c.setEditField(Convert.toBool(_json.get("editable"), true));
            c.setSearchField(Convert.toBool(_json.get("searchable"), false));
            List<Verify> verifyList = Lists.newArrayList();
            if (_json.containsKey("verify")) {
                String vvs = Convert.toStr(_json.get("verify"));
                if (vvs.length() > 0) {
                    String[] vvArray = StrUtil.splitToArray(vvs, ',');
                    for (String _v : vvArray) {
                        verifyList.add(new Verify(_v));
                    }
                }
                c.setVerifyList(verifyList);
            } else {
                c.setVerifyList(verifyList);
            }
        }
    }
    // 生成代码
    String tmpl = GenUtils.getParam(params, "tmpl");
    if (StrUtil.isEmpty(tmpl)) {
        generatorCode(table, zip);
    } else {
        generatorAdvCodeOnlyWeb(tmpl, table, columns, params, zip);
    }
    IOUtils.closeQuietly(zip);
    return outputStream.toByteArray();
}
 
Example 19
Source File: GenServiceImpl.java    From kvf-admin with MIT License 4 votes vote down vote up
@Override
    public GenConfigVO init(String tableName, String tableType, String tableComment) {
        GenConfigVO genConfig = new GenConfigVO(tableName, tableType, tableComment);
        String moduleName = tableName.substring(0, tableName.indexOf("_"));
        String funName = StrUtil.toCamelCase(tableName.substring(tableName.indexOf("_") + 1));
        genConfig.setModuleName(moduleName).setFunName(funName).setFirstCapFunName(StrUtil.upperFirst(funName));

        // 获取数据库表所有列字段数据
        List<TableColumnDTO> tableColumnDTOS = tableService.listTableColumn(tableName);

        // 获取并设置实体类所有需要导入的java包集合
        Set<String> sets = AuxiliaryKit.getEntityImportPkgs(tableColumnDTOS);
        genConfig.setPkgs(sets);

        // 处理表列数据
        tableColumnDTOS = AuxiliaryKit.handleTableColumns(tableColumnDTOS);
        AuxiliaryKit.handleAndSetAllColumnsValueRelations(tableColumnDTOS);
        genConfig.setAllColumns(tableColumnDTOS);

        // 设置主键
        Optional<TableColumnDTO> tOptional = tableColumnDTOS
                .stream().filter(tc -> tc.getColumnKey().equals("PRI")).findFirst();
        TableColumnDTO tableColumn = tOptional.get();
        genConfig.setPrimaryKey(tableColumn.getColumnName());
        genConfig.setPkCamelCase(StrUtil.toCamelCase(tableColumn.getColumnName()));
        genConfig.setFirstCapPk(StrUtil.upperFirst(genConfig.getPkCamelCase()));

        // 处理表列值说明关系
        List<ColumnConfigDTO> columnConfigDTOS = AuxiliaryKit.tableColumnsToColumnConfigs(tableColumnDTOS);
        AuxiliaryKit.handleAndSetColumnsValueRelations(columnConfigDTOS);
        genConfig.setColumns(columnConfigDTOS);

        // 读取半设置按钮配置信息并处理
//        String buttonInfo = FileUtil.readString(
//                new File(ClassUtil.getClassPath() + ConfigConstant.BUTTON_JSON_REL_PATH), "UTF-8");
        String buttonInfo = FileKit.readString(ConfigConstant.BUTTON_JSON_REL_PATH);
        JSONObject jsonObject = JSONUtil.parseObj(buttonInfo);
        JSONArray headButtons = JSONUtil.parseArray(jsonObject.get(ConfigConstant.HEAD_BUTTON_KEY));
        JSONArray rowButtons = JSONUtil.parseArray(jsonObject.get(ConfigConstant.ROW_BUTTON_KEY));
        List<ButtonConfigDTO> headBtnConfigs = JSONUtil.toList(headButtons, ButtonConfigDTO.class);
        List<ButtonConfigDTO> rowBtnConfigs = JSONUtil.toList(rowButtons, ButtonConfigDTO.class);
        List<ButtonConfigDTO> headCollect = headBtnConfigs.stream()
                .peek(hc -> hc.setPerId(hc.getPerId().replace("{m}", moduleName).replace("{f}", funName)))
                .collect(Collectors.toList());
        List<ButtonConfigDTO> rowCollect = rowBtnConfigs.stream()
                .peek(hc -> hc.setPerId(hc.getPerId().replace("{m}", moduleName).replace("{f}", funName)))
                .collect(Collectors.toList());
        genConfig.setHeadButtons(headCollect);
        genConfig.setRowButtons(rowCollect);
        genConfig.setQueryColumns(new ArrayList<>());

        return genConfig;
    }
 
Example 20
Source File: StringUtils.java    From eladmin with Apache License 2.0 4 votes vote down vote up
/**
 * 根据ip获取详细地址
 */
public static String getHttpCityInfo(String ip) {
    String api = String.format(ElAdminConstant.Url.IP_URL, ip);
    JSONObject object = JSONUtil.parseObj(HttpUtil.get(api));
    return object.get("addr", String.class);
}