Java Code Examples for net.sf.json.JSONObject#toString()

The following examples show how to use net.sf.json.JSONObject#toString() . 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: CustomMenuController.java    From JavaWeb with Apache License 2.0 6 votes vote down vote up
@PostMapping(value="/testPersonalizedMenuMatch",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String testPersonalizedMenuMatch(HttpServletRequest request, 
 						  	   	            HttpServletResponse response){
	try{
		String url = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token="+CoreControllerHelp.getAccessToken().get("access_token");
		JSONObject jo = new JSONObject();
		jo.put("user_id", "weixin");//TODO
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		headers.setContentType(type);
		HttpEntity<String> formEntity = new HttpEntity<String>(jo.toString(), headers);
		return new RestTemplate().postForObject(url, formEntity, String.class);
	}catch(Exception e){
		//do nothing
	}
	return null;
}
 
Example 2
Source File: HttpUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
/**
 * post请求
 * @param url
 * @param json
 * @return
 */
public static JSONObject doPost(String url,JSONObject json){
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;
    try {
        StringEntity s = new StringEntity(json.toString(),"UTF-8");
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");
        post.setHeader("Accept-Charset","UTF-8");
        
        System.out.println(StringUtil.inputStreamToString(post.getEntity().getContent(), "UTF-8"));
        
        HttpResponse res = client.execute(post);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(res.getEntity());// 返回json格式:
            response = JSONObject.fromObject(result);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return response;
}
 
Example 3
Source File: RoleController.java    From JavaWeb with Apache License 2.0 6 votes vote down vote up
@PostMapping(value="/allotRoleAuthority",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String allotRoleAuthority(HttpServletRequest request, 
		  			        	 HttpServletResponse response,
		  			        	 @RequestBody JsonNode jsonNode) {
	JSONObject jo = new JSONObject();
	try{
		String roleId = jsonNode.get("roleId").asText();//角色ID
		String moduleId = jsonNode.get("moduleId").asText();//模块ID(支持多个,用逗号隔开)
		roleService.allotRoleAuthority(roleId, moduleId);
		jo.put("message", "用户分配角色失败");
	}catch(Exception e){
		jo.put("message", "用户分配角色成功");
	}
	return jo.toString();
}
 
Example 4
Source File: QueryParamUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 将结果集转化为列表json格式
 * @param result 结果集
 * @param size 总大小
 * @return 处理好的json格式
 */
@SuppressWarnings("unchecked")
public static String getJson(List<Map<String, Object>> result,Long size){
	JSONObject main = new JSONObject();
	JSONArray rows = new JSONArray();
	main.put("total",size );
	for(Map m:result){
		JSONObject item = new JSONObject();
		Iterator  it =m.keySet().iterator();
		while(it.hasNext()){
			String key = (String) it.next();
			String value =String.valueOf(m.get(key));
			key = key.toLowerCase();
			if(key.contains("time")||key.contains("date")){
				value = datatimeFormat(value);
			}
			item.put(key,value );
		}
		rows.add(item);
	}
	main.put("rows", rows);
	return main.toString();
}
 
Example 5
Source File: KunpengScan.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
private String checkPlugins(){
    JSONObject cfg = new JSONObject();
    cfg.put("timeout",Integer.parseInt(getParam().getOrDefault("timeout","15").toString()));
    cfg.put("aider","http://"+identifier);
    cfg.put("extra_plugin_path", new File(JSONPlugin.jsonPath).getAbsolutePath());
    Kunpeng.INSTANCE.SetConfig(cfg.toString());
    JSONObject jsonObject = new JSONObject();
    if (getParam().containsKey("netloc"))
        jsonObject.put("netloc",getParam().getOrDefault("netloc",""));
    if (getParam().containsKey("target"))
        jsonObject.put("target",getParam().getOrDefault("target","web"));
    if (getParam().containsKey("type"))
        jsonObject.put("type",getParam().getOrDefault("type","web"));
    String check_json = jsonObject.toString();
    String checkResult = Kunpeng.INSTANCE.Check(check_json);
    if (CheckUtils.isJson(checkResult)){
        return StrUtils.formatJson(checkResult);
    }else{
        String s = Native.toString(Native.toByteArray(checkResult), "UTF-8");
        return StrUtils.formatJson(s);
    }
}
 
Example 6
Source File: GeoServerGetCoverageCommand.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public String computeResults(final OperationParams params) throws Exception {
  if (parameters.size() != 1) {
    throw new ParameterException("Requires argument: <coverage name>");
  }

  if ((workspace == null) || workspace.isEmpty()) {
    workspace = geoserverClient.getConfig().getWorkspace();
  }

  cvgName = parameters.get(0);

  final Response getCvgResponse =
      geoserverClient.getCoverage(workspace, cvgstore, cvgName, false);

  if (getCvgResponse.getStatus() == Status.OK.getStatusCode()) {
    final JSONObject jsonResponse = JSONObject.fromObject(getCvgResponse.getEntity());
    return "\nGeoServer coverage info for '" + cvgName + "': " + jsonResponse.toString(2);
  }
  final String errorMessage =
      "Error getting GeoServer coverage info for "
          + cvgName
          + ": "
          + getCvgResponse.readEntity(String.class)
          + "\nGeoServer Response Code = "
          + getCvgResponse.getStatus();
  return handleError(getCvgResponse, errorMessage);
}
 
Example 7
Source File: IngestionResource.java    From oodt with Apache License 2.0 5 votes vote down vote up
private String encodeIngestResponseAsJSON(boolean success, String msg) {
  Map<String, Object> resMap = new ConcurrentHashMap<String, Object>();
  resMap.put("success", success);
  resMap.put("msg", msg);
  JSONObject resObj = new JSONObject();
  resObj.putAll(resMap);
  return resObj.toString();

}
 
Example 8
Source File: StandardStats.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
public void setClusterInfoMap(Map<String, Object> clusterInfoMap) {
    if (clusterInfoJson == null) {
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.fromObject(clusterInfoMap);
            clusterInfoJson = jsonObject.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
    this.clusterInfoMap = clusterInfoMap;
}
 
Example 9
Source File: StringUtil.java    From Leo with Apache License 2.0 5 votes vote down vote up
/**
 * 把json串中的uncode编码转换为字符串显示,转换失败返回原json串
 * @param jsonStr
 * @return String
 */
public static String getStrFromJson(String jsonStr) {
	try {
		JSONObject tempJSON = JSONObject.fromObject(jsonStr);
		return tempJSON.toString();
	} catch (Exception e) {
		return jsonStr;
	}

}
 
Example 10
Source File: PedigreeResource.java    From oodt with Apache License 2.0 5 votes vote down vote up
private String encodePedigreeAsJson(PedigreeTree up, PedigreeTree down) {
  Map<String, Object> output = new ConcurrentHashMap<String, Object>();
  if (up != null) {
    output.put("upstream", this.encodePedigreeTreeAsJson(up.getRoot()));
  }
  if (down != null) {
    output.put("downstream", this.encodePedigreeTreeAsJson(down.getRoot()));
  }
  JSONObject json = new JSONObject();
  json.put("pedigree", output);
  return json.toString();
}
 
Example 11
Source File: JSONHelper.java    From jeecg with Apache License 2.0 4 votes vote down vote up
public static String map2json(Object object) {
	JSONObject jsonObject = JSONObject.fromObject(object);
	return jsonObject.toString();
}
 
Example 12
Source File: JSONHelper.java    From jeewx with Apache License 2.0 4 votes vote down vote up
public static String map2json(Object object) {
	JSONObject jsonObject = JSONObject.fromObject(object);
	return jsonObject.toString();
}
 
Example 13
Source File: MainServer.java    From JrebelBrainsLicenseServerforJava with Apache License 2.0 4 votes vote down vote up
private void jrebelLeasesHandler(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    String clientRandomness = request.getParameter("randomness");
    String username = request.getParameter("username");
    String guid = request.getParameter("guid");
    System.out.println(((Request) request).getParameters());
    boolean offline = Boolean.parseBoolean(request.getParameter("offline"));
    String validFrom = "null";
    String validUntil = "null";
    if (offline) {
        String clientTime = request.getParameter("clientTime");
        String offlineDays = request.getParameter("offlineDays");
        //long clinetTimeUntil = Long.parseLong(clientTime) + Long.parseLong(offlineDays)  * 24 * 60 * 60 * 1000;
        long clinetTimeUntil = Long.parseLong(clientTime) + 180L * 24 * 60 * 60 * 1000;
        validFrom = clientTime;
        validUntil = String.valueOf(clinetTimeUntil);
    }
    baseRequest.setHandled(true);
    String jsonStr = "{\n" +
            "    \"serverVersion\": \"3.2.4\",\n" +
            "    \"serverProtocolVersion\": \"1.1\",\n" +
            "    \"serverGuid\": \"a1b4aea8-b031-4302-b602-670a990272cb\",\n" +
            "    \"groupType\": \"managed\",\n" +
            "    \"id\": 1,\n" +
            "    \"licenseType\": 1,\n" +
            "    \"evaluationLicense\": false,\n" +
            "    \"signature\": \"OJE9wGg2xncSb+VgnYT+9HGCFaLOk28tneMFhCbpVMKoC/Iq4LuaDKPirBjG4o394/UjCDGgTBpIrzcXNPdVxVr8PnQzpy7ZSToGO8wv/KIWZT9/ba7bDbA8/RZ4B37YkCeXhjaixpmoyz/CIZMnei4q7oWR7DYUOlOcEWDQhiY=\",\n" +
            "    \"serverRandomness\": \"H2ulzLlh7E0=\",\n" +
            "    \"seatPoolType\": \"standalone\",\n" +
            "    \"statusCode\": \"SUCCESS\",\n" +
            "    \"offline\": " + String.valueOf(offline) + ",\n" +
            "    \"validFrom\": " + validFrom + ",\n" +
            "    \"validUntil\": " + validUntil + ",\n" +
            "    \"company\": \"Administrator\",\n" +
            "    \"orderId\": \"\",\n" +
            "    \"zeroIds\": [\n" +
            "        \n" +
            "    ],\n" +
            "    \"licenseValidFrom\": 1490544001000,\n" +
            "    \"licenseValidUntil\": 1691839999000\n" +
            "}";

    JSONObject jsonObject = JSONObject.fromObject(jsonStr);
    if (clientRandomness == null || username == null || guid == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } else {
        JrebelSign jrebelSign = new JrebelSign();
        jrebelSign.toLeaseCreateJson(clientRandomness, guid, offline, validFrom, validUntil);
        String signature = jrebelSign.getSignature();
        jsonObject.put("signature", signature);
        jsonObject.put("company", username);
        String body = jsonObject.toString();
        response.getWriter().print(body);
    }
}
 
Example 14
Source File: CustomMenuController.java    From JavaWeb with Apache License 2.0 4 votes vote down vote up
@PostMapping(value="/createMenu",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String createMenu(HttpServletRequest request, 
 						     HttpServletResponse response){
	try{
		String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+CoreControllerHelp.getAccessToken().get("access_token");
		JSONObject level_1_1 = new JSONObject();
		level_1_1.put("type", "view");
		level_1_1.put("name", "一级菜单1");
		level_1_1.put("url", "www.baidu.com");
		JSONObject level_1_2 = new JSONObject();
		level_1_2.put("name", "一级菜单2");
		JSONObject level_1_2_1 = new JSONObject();
		level_1_2_1.put("type", "view");
		level_1_2_1.put("name", "二级菜单1");
		level_1_2_1.put("url", "www.baidu.com");
		JSONObject level_1_2_2 = new JSONObject();
		level_1_2_2.put("type", "view");
		level_1_2_2.put("name", "二级菜单2");
		level_1_2_2.put("url", "www.baidu.com");
		JSONObject level_1_2_3 = new JSONObject();
		level_1_2_3.put("type", "view");
		level_1_2_3.put("name", "二级菜单3");
		level_1_2_3.put("url", "www.baidu.com");
		JSONArray ja = new JSONArray();
		ja.add(level_1_2_1);
		ja.add(level_1_2_2);
		ja.add(level_1_2_3);
		level_1_2.put("sub_button", ja);
		JSONObject level_1_3 = new JSONObject();
		level_1_3.put("type", "view");
		level_1_3.put("name", "一级菜单3");
		level_1_3.put("url", "www.sina.com");
		JSONObject jo = new JSONObject();
		JSONArray jaja = new JSONArray();
		jaja.add(level_1_1);
		jaja.add(level_1_2);
		jaja.add(level_1_3);
		jo.put("button", ja);
		
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		headers.setContentType(type);
		HttpEntity<String> formEntity = new HttpEntity<String>(jo.toString(), headers);
		return new RestTemplate().postForObject(url, formEntity, String.class);
	}catch(Exception e){
		//do nothing
	}
	return null;
}
 
Example 15
Source File: AllOpenController.java    From JavaWeb with Apache License 2.0 4 votes vote down vote up
/**
httpServletRequest.getRequestURI()             /yuhong_server/app/html/home.html
httpServletRequest.getRequestURL().toString()  http://localhost:8080/yuhong_server/app/html/home.html 
httpServletRequest.getServletPath()            /app/html/home.html
*/

@PostMapping(value="/userWebLogin",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String login(HttpServletRequest request, 
		  			HttpServletResponse response,
		  			@RequestBody JsonNode jsonNode
		  			/** @RequestBody User user */
		  			/** @ModelAttribute User user */) {
	JSONObject jo = new JSONObject();
	try{
		//Xyz xyz = mapper.readValue(jsonNode.toString(), Xyz.class);
		/** JSONArray相关转化常用的方法如下:
		    List<ProjectMaterialsOut> list = (List<ProjectMaterialsOut>)JSONArray.toCollection(ja, ProjectMaterialsOut.class);
		    JSONArray ja = JSONArray.fromObject(JSONArray.toArray(ja,c));	
		 */
		String username = jsonNode.get("username").asText();//用户名
		String password = jsonNode.get("password").asText();//密码
		String code = jsonNode.get("code").asText();//这个是用户输入的验证码
		String sessionCode = getSessionCode();//这个是session中的验证码
		if(!code.equalsIgnoreCase(sessionCode)){//验证码校验忽略大小写
			jo.put(Constant.MESSAGE, "验证码错误");
			jo.put(Constant.STATUS, Constant.STATUS_FAIL);
		}else{
			Map<String,String> map = new HashMap<>();
			map.put("username", username);
			map.put("password", new SimpleHash("SHA-1", username, password).toString());
			User user = userService.getUserByUsernameAndPassword(map);
			if(user==null){
				jo.put(Constant.MESSAGE, "用户名或密码错误");
				jo.put(Constant.STATUS, Constant.STATUS_FAIL);
			}else{
				//同一账号登录后不能再登录的实现,未经大量验证,效果有待后续观察
				if(ChartController.user.get(username)!=null){
					jo.put(Constant.MESSAGE, "该账号已登录");
			    	jo.put(Constant.STATUS, Constant.STATUS_FAIL);
				}else{
					//shiro加入身份验证
				    UsernamePasswordToken token = new UsernamePasswordToken(map.get("username"), map.get("password")); 
			    	ShiroUtil.getSubject().login(token);
					//获得角色信息
					List<Role> roleList = userService.getUserRoles(user.getUserid());
					if(roleList.size()>0){
						int superAdminFlag = getSuperAdminFlag(roleList);
						//moduleList = userService.getUserMenu(roleList,superAdminFlag);
						//operationList = userService.getUserOperation(roleList,superAdminFlag);
						List<Module> allModuleList = userService.getUserAllModule(roleList, superAdminFlag);
						ModuleListVO moduleListVO = getNeedList(allModuleList);
						//获得当前角色左侧树形菜单列表
						List<Module> moduleList = moduleListVO.getModuleList();
						//获得当前角色右侧菜单对应的所有操作列表
						List<Module> operationList = moduleListVO.getOperationList();
						//获得顶层菜单列表,用于对关键操作进行路径检查
						List<Module> topModuleList = moduleListVO.getTopModuleList();
						moduleList = FunctionAndOperationHandler.setTreeList(moduleList, null);
						//获得权限路径检查的正则表达式
						String authorityChaekPath = getAuthorityChaekPath(topModuleList);
						//获得服务器IP地址及端口号
						String ipAddressAndPort = getIpAddressAndPort(request);
						ShiroUtil.setAttribute(Constant.SESSION_USER, user);
						ShiroUtil.setAttribute(Constant.SESSION_ROLE, roleList);
						ShiroUtil.setAttribute(Constant.SESSION_MODULE, moduleList);
						ShiroUtil.setAttribute(Constant.SESSION_OPERATION, operationList);
						ShiroUtil.setAttribute(Constant.AUTHORITY_CHAEK_PATH, authorityChaekPath);
						//ShiroUtil.setAttribute(Constant.IP_ADDRESS_PORT,ipAddressAndPort);
						jo.put(Constant.MESSAGE, "登录成功");
						jo.put("user", user);
						jo.put("role", roleList);
						jo.put("module", moduleList);
						jo.put("operation", operationList);
						jo.put("ipAddressPort", ipAddressAndPort);
						jo.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					}else{
						jo.put(Constant.MESSAGE, "该用户未分配角色");
				    	jo.put(Constant.STATUS, Constant.STATUS_FAIL);
					}
				}
			}
		}
	}catch(Exception e){
		jo.put(Constant.MESSAGE, "服务器内部异常");
    	jo.put(Constant.STATUS, Constant.STATUS_FAIL);
	}
	//从后台代码获取国际化信息
	//ResourceBundle resourceBundle = ResourceBundleHandler.getResourceBundle(request);
	//System.out.println(resourceBundle.getString("username"));
	return jo.toString();
}
 
Example 16
Source File: ErpMenuServiceImpl.java    From erp-framework with MIT License 4 votes vote down vote up
@Override
public String getTreeMenuList(String roleId) {
    DtreeResponse response = dtreeService.getMenuDtreeResponse(roleId);
    JSONObject obj = JSONObject.fromObject(response);
    return obj.toString();
}
 
Example 17
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
public static String string2json(String key, String value) {
	JSONObject object = new JSONObject();
	object.put(key, value);
	return object.toString();
}
 
Example 18
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 3 votes vote down vote up
protected String createFeatureTypeJson(final String featureTypeName) {
  final JSONObject featTypeJson = new JSONObject();

  featTypeJson.put("name", featureTypeName);

  final JSONObject jsonObj = new JSONObject();
  jsonObj.put("featureType", featTypeJson);

  return jsonObj.toString();
}
 
Example 19
Source File: JSONHelper.java    From jeecg with Apache License 2.0 2 votes vote down vote up
/***
 * 将JSON对象序列化为JSON文本
 * 
 * @param jsonObject
 * @return
 */
public static String toJSONString(JSONObject jsonObject) {
	return jsonObject.toString();
}
 
Example 20
Source File: JSONHelper.java    From jeewx with Apache License 2.0 2 votes vote down vote up
/***
 * 将JSON对象序列化为JSON文本
 * 
 * @param jsonObject
 * @return
 */
public static String toJSONString(JSONObject jsonObject) {
	return jsonObject.toString();
}