Example usage for org.json.simple JSONValue toJSONString

List of usage examples for org.json.simple JSONValue toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONValue toJSONString.

Prototype

public static String toJSONString(Object value) 

Source Link

Usage

From source file:de.cgarbs.lib.json.JSONDataModel.java

/**
 * Converts the DataModel to JSON/*from  w  ww. j  a va  2  s .c  o  m*/
 * @param model the DataModel to convert
 * @return JSON representation of the DataModel
 * @throws JSONException when there is an error during the JSON conversion
 * @throws DataException when there is an error during value retrieval from the DataModel
 */
static String convertToJSON(final DataModel model) throws JSONException, DataException {
    final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
    for (final String key : model.getAttributeKeys()) {
        attributes.put(key, prepareForJSON(model.getValue(key)));
    }

    final Map<String, Object> json = new LinkedHashMap<String, Object>();
    json.put(IDENTIFIER_FIELD, IDENTIFIER);
    json.put(VERSION_FIELD, VERSION);
    json.put(ATTRIBUTE_FIELD, attributes);

    return JSONValue.toJSONString(json);
}

From source file:edu.anu.spice.Evaluation.java

@SuppressWarnings("unchecked")
@Override/*from w w w . j a  v a 2 s.co  m*/
public String toJSONString() {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("tp", new Integer(tp));
    jsonObj.put("fp", new Integer(fp));
    jsonObj.put("fn", new Integer(fn));
    jsonObj.put("f", new Double(f));
    jsonObj.put("pr", new Double(pr));
    jsonObj.put("re", new Double(re));
    jsonObj.put("numImages", new Integer(numImages));
    return JSONValue.toJSONString(jsonObj);
}

From source file:com.mansoor.uncommon.configuration.JsonConfiguration.java

/**
 * {@inheritDoc}/*from   ww  w . j  a  v  a  2 s.c o m*/
 */
@SuppressWarnings("unchecked")
protected void storeConfiguration(final File file) throws IOException {
    final String value = JSONValue.toJSONString(properties);
    saveFile(file, value);
}

From source file:com.sk89q.squirrelid.util.HttpRequest.java

/**
 * Set the content body to a JSON object with the content type of "application/json".
 *
 * @param object the object to serialize as JSON
 * @return this object/*from   w ww.  j av  a 2s  . com*/
 * @throws java.io.IOException if the object can't be mapped
 */
public HttpRequest bodyJson(Object object) throws IOException {
    contentType = "application/json";
    body = JSONValue.toJSONString(object).getBytes();
    return this;
}

From source file:com.ikanow.aleph2.storm.harvest_technology.RemoteStormController.java

@Override
public void submitJob(String job_name, String input_jar_location, StormTopology topology) throws Exception {
    logger.info("Submitting job: " + job_name + " jar: " + input_jar_location);
    logger.info("submitting jar");
    String remote_jar_location = StormSubmitter.submitJar(remote_config, input_jar_location);
    String json_conf = JSONValue.toJSONString(remote_config);
    logger.info("submitting topology");
    client.submitTopology(job_name, remote_jar_location, json_conf, topology);
}

From source file:com.vizury.PushNotification.Engine.Sender.java

public MulticastResult sendMultiCastMessage(Message message, List<String> registrationIds,
        List<String> cookieList) throws IOException {
    logger.debug("Entering sendMessage");
    if (nonNull(registrationIds).isEmpty()) {
        logger.error("SendMessage, registrationIds cannot be empty ");
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }/*from   w ww. j  a  v a2 s .  co  m*/
    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
    setJsonField(jsonRequest, JSON_PAYLOAD, message.getPayloadData());

    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.debug("JSON request: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        logger.debug("IOException posting to GCM" + e.getMessage());
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.debug("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.debug("Exception reading response: " + e.getMessage());
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        logger.error("IOException reading response, returning null result" + e.getMessage());
        return null;
    }
    logger.debug("JSON response: " + responseBody);

    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();

        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        int count = 0;
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                String cookie = cookieList.get(count);
                count++;
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).cookieValue(cookie).build();
                builder.addResult(result);
            }
        }
        logger.debug("Finished sendMessage");
        return builder.build();
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:myproject.MyServer.java

public static void Delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from  www . j a v  a 2s  . co m*/
        String jsonString = IOUtils.toString(request.getInputStream());
        JSONObject json = (JSONObject) JSONValue.parse(jsonString);
        Long student_id = (Long) json.get("student_id");

        String query = String.format("DELETE FROM student " + "WHERE student_id=%d", student_id);

        database.runUpdate(query);

        JSONObject output = new JSONObject();
        output.put("result", true);
        response.getWriter().write(JSONValue.toJSONString(output));
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}

From source file:com.turt2live.xmail.mail.attachment.Attachment.java

/**
 * Converts this attachment to JSON in to format <br>
 * <code>{"type":{@link #getType()}.name(), "content":{@link #getSerializedContent()}}</code>
 *
 * @return the valid JSON//from  w  w  w .  j a v a  2s.  com
 */
public final String toJson() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("type", getType().name());
    map.put("content", getSerializedContent());
    return JSONValue.toJSONString(map);
}

From source file:com.turt2live.xmail.mail.attachment.ItemAttachment.java

@Override
public Object getSerializedContent() {
    Map<String, Object> serial = item.serialize();
    if (serial.get("meta") != null) {
        ItemMeta itemmeta = item.getItemMeta();
        Map<String, Object> meta = itemmeta.serialize();
        Map<String, Object> meta2 = new HashMap<String, Object>();
        for (String key : meta.keySet()) {
            meta2.put(key, meta.get(key));
        }/*from   w  w  w .j  a  va 2s  .  co m*/
        for (String key : meta2.keySet()) {
            Object o = meta2.get(key);
            if (o instanceof ConfigurationSerializable) {
                ConfigurationSerializable serial1 = (ConfigurationSerializable) o;
                Map<String, Object> serialed = recursiveSerialization(serial1);
                meta2.put(key, serialed);
            }
        }
        meta = meta2;
        serial.put("meta", meta);
    }
    return JSONValue.toJSONString(serial);
}

From source file:me.sonarbeserk.lockup.utils.UUIDFetcher.java

@SuppressWarnings("unchecked")
private static String buildBody(List<String> names) {
    List<JSONObject> lookups = new ArrayList<JSONObject>();
    for (String name : names) {
        JSONObject obj = new JSONObject();
        obj.put("name", name);
        obj.put("agent", AGENT);
        lookups.add(obj);//ww w . j  a  v a  2s .  c  om
    }
    return JSONValue.toJSONString(lookups);
}