List of usage examples for org.json.simple JSONValue toJSONString
public static String toJSONString(Object value)
From source file:myproject.MyServer.java
public static void List(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/*from w w w. j a v a 2s .c o m*/ String query = "SELECT * FROM student"; String result = database.runQuery(query); response.getWriter().write(result); } catch (Exception ex) { JSONObject output = new JSONObject(); output.put("error", "Connection failed: " + ex.getMessage()); response.getWriter().write(JSONValue.toJSONString(output)); } }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendPost() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {/*from w ww .j a v a 2 s . c om*/ //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenPost.php"; //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON URL obj = new URL(url); //Creamos un objeto de conexin HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //Aadimos la cabecera con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //Creamos los parametros para enviar String urlParameters = "json=" + jsonString; // Enviamos los datos por POST con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Capturamos la respuesta del servidor int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } //Mostramos la respuesta del servidor por consola System.out.println(response); //cerramos la conexin in.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:myproject.MyServer.java
public static void Query(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/*w w w. j a v a2 s .c o m*/ String jsonString = IOUtils.toString(request.getInputStream()); JSONObject json = (JSONObject) JSONValue.parse(jsonString); String query = (String) json.get("query"); String result = database.runQuery(query); response.getWriter().write(result); } catch (Exception ex) { JSONObject output = new JSONObject(); output.put("error", "Connection failed: " + ex.getMessage()); response.getWriter().write(JSONValue.toJSONString(output)); } }
From source file:mikolaj.torrent.actions.Result.java
public void saveJson(Object array) { this.data = JSONValue.toJSONString(array); }
From source file:de.cgarbs.lib.json.type.JSONType.java
@Override public String toJSONString() { final Map<String, Object> json = new LinkedHashMap<String, Object>(); json.put(CLASS_FIELD, getJSONClassName()); json.put(VERSION_FIELD, getJSONClassVersion()); json.put(ATTRIBUTE_FIELD, getJSONAttributes()); return JSONValue.toJSONString(json); }
From source file:com.jadarstudios.rankcapes.bukkit.network.packet.S0PacketPlayerCapesUpdate.java
@Override public void write(ByteBuffer data) throws BufferOverflowException, ReadOnlyBufferException { data.put((byte) this.type.ordinal()); String players = JSONValue.toJSONString(this.playersMap); writeString(players, data);/*from ww w . j a v a 2 s . co m*/ }
From source file:logging.report.PGRecord.java
public PGRecord(PGLogCategory category, String uid, long time, long execTime, Object data) { this.category = category; this.uid = uid; this.lTime = time; this.time = String.valueOf(time); this.execTime = String.valueOf(execTime); this.data = JSONValue.toJSONString(data); }
From source file:de.fhg.fokus.odp.portal.managedatasets.utils.HashMapUtils.java
/** * Meta data to map./*w ww . j av a2 s.co m*/ * * @param metaData * the meta data * @return the hash map */ public static HashMap<String, String> metaDataToMap(MetaDataBean metaData) { HashMap<String, String> metaDataMap = new HashMap<String, String>(); HashMap<String, String> extrasMap = new HashMap<String, String>(); List<Map<String, String>> resourcesList = new ArrayList<Map<String, String>>(); extrasMap.put("temporal_coverage_from", metaData.getTemporal_coverage_from()); extrasMap.put("temporal_coverage_to", metaData.getTemporal_coverage_to()); extrasMap.put("temporal_granularity", metaData.getTemporal_granularity()); extrasMap.put("geographical_coverage", metaData.getGeographical_coverage()); extrasMap.put("geographical_granularity", metaData.getGeographical_granularity()); extrasMap.put("date_released", DateUtils.dateToStringTemporalCoverage(metaData.getDate_released())); extrasMap.put("others", metaData.getOthers()); for (Resource resource : metaData.getResources()) { Map<String, String> resourceMap = new HashMap<String, String>(); if (!resource.getUrl().isEmpty() && !resource.getFormat().isEmpty()) { resourceMap.put("url", resource.getUrl()); resourceMap.put("format", resource.getFormat().toUpperCase()); resourceMap.put("description", resource.getDescription()); resourceMap.put("language", resource.getLanguage()); resourcesList.add(resourceMap); } } metaDataMap.put("extras", JSONValue.toJSONString(extrasMap)); metaDataMap.put("resources", JSONValue.toJSONString(resourcesList)); if (metaData.getTags().isEmpty()) { metaDataMap.put("tags", "[]"); } else { StringBuilder tagsBuilder = new StringBuilder(); for (String tag : metaData.getTags().split(",")) { tagsBuilder.append("\"" + tag.trim() + "\","); } // remove trailing comma tagsBuilder = tagsBuilder.deleteCharAt(tagsBuilder.length() - 1); metaDataMap.put("tags", "[" + tagsBuilder.toString().trim() + "]"); } metaDataMap.put("groups", JSONValue.toJSONString(metaData.getGroups())); metaDataMap.put("title", "\"" + metaData.getTitle() + "\""); metaDataMap.put("name", "\"" + metaData.getName() + "\""); metaDataMap.put("author", "\"" + metaData.getAuthor() + "\""); metaDataMap.put("author_email", "\"" + metaData.getAuthor_email() + "\""); metaDataMap.put("url", "\"" + metaData.getUrl() + "\""); metaDataMap.put("notes", "\"" + metaData.getNotes() + "\""); metaDataMap.put("license_id", "\"" + metaData.getLicense_id() + "\""); metaDataMap.put("version", "\"" + metaData.getVersion() + "\""); metaDataMap.put("maintainer", "\"" + metaData.getMaintainer() + "\""); metaDataMap.put("maintainer_email", "\"" + metaData.getMaintainer_email() + "\""); metaDataMap.put("metadata_created", "\"" + DateUtils.dateToStringMetaDate(metaData.getMetadata_created()) + "\""); metaDataMap.put("metadata_modified", "\"" + metaData.getMetadata_modified() + "\""); log.info("JSON String for create metadata: " + metaDataMap.toString()); return metaDataMap; }
From source file:deck36.storm.plan9.Plan9RabbitMQRouterBolt.java
@Override public void execute(Tuple tuple) { String msg = JSONValue.toJSONString(tuple.getValueByField("badge")); _collector.emit(tuple, new Values(msg, _exchange, _routingKey)); _collector.ack(tuple);/*from w w w . j a va 2 s . co m*/ }
From source file:ca.xecure.easychip.CommonUtilities.java
public static void http_post(String endpoint, Map<String, String> params) throws IOException { URL url;/*from www . j a v a 2 s. c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } String body = JSONValue.toJSONString(params); Log.v(LOG_TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }