Example usage for org.json.simple JSONObject toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:co.edu.uniandes.ecos.statusquo.services.PacienteService.java

@DELETE
@Produces(MediaType.APPLICATION_JSON)//w  ww  . j  a  v a  2  s.  c  o  m
public Response eliminarPaciente(Paciente paciente) {

    final JSONObject rta = new JSONObject();

    try {
        pacienteService.save(paciente);
        rta.put("paciente_id", paciente.getId());
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        return Response.status(500).header("Access-Control-Allow-Origin", "*").entity(0).build();
    }

    return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(rta.toJSONString()).build();
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.MQLQueryWrapper.java

@SuppressWarnings("unchecked")
public MQLQueryWrapper(String namespace, String value) {
    this.value = value;
    JSONObject obj = new JSONObject();
    JSONArray key = new JSONArray();
    JSONArray type = new JSONArray();
    obj.put("mid", null);
    obj.put("type", type);
    JSONObject contents = new JSONObject();
    contents.put("namespace", namespace);
    contents.put("value", QueryMQL.encodeMQL(value));
    key.add(contents);//from  ww  w .j ava2  s . com
    obj.put("key", key);
    this.MQLquery = StringEscapeUtils.unescapeJavaScript(obj.toJSONString());
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.engine.parser.Task.java

@SuppressWarnings("unchecked")
@Override/*from w  w w .j av a 2s.  c  om*/
public String toJSONString() {

    JSONObject obj = new JSONObject();
    obj.put("point", getPosition());
    obj.put("tolerance", getTolerance());
    // TODO arrival time, delay, and lifetime in JSON string?

    JSONArray act = new JSONArray();
    for (IAction a : getActionList()) {
        act.add(a);
    }
    obj.put("actions", act);

    return obj.toJSONString();
}

From source file:de.metalcon.musicStorageServer.protocol.UpdateRequestTest.java

@SuppressWarnings("unchecked")
@Before/*from   w  w w . j av a 2 s.  co m*/
public void setUp() {
    // meta data
    final JSONObject metaDataUpdate = new JSONObject();
    metaDataUpdate.put("title", "My Great Song");
    metaDataUpdate.put("album", "Testy Forever");
    metaDataUpdate.put("artist", "Testy");
    metaDataUpdate.put("license", "General Less AllYouCanEat License");
    metaDataUpdate.put("date", "1991-11-11");
    metaDataUpdate.put("description", "All your cookies belong to me!");
    VALID_UPDATE_META_DATA = metaDataUpdate.toJSONString();
}

From source file:hoot.services.controllers.job.ExportJobResourceTest.java

@Test
@Category(UnitTest.class)
public void testProcessForWFS() throws Exception {
    String[] hostParts = DB_HOST.split(":");
    String pgUrl = "host='" + hostParts[0] + "' port='" + hostParts[1] + "' user='" + DB_USER_ID
            + "' password='" + DB_PASSWORD + "' dbname='" + WFS_STORE_DB + "'";

    String params = "{\"translation\":\"MGCP.js\",\"inputtype\":\"db\",\"input\":\"ToyTestA\",\"outputtype\":\"wfs\",\"removereview\" : \"false\"}";

    JSONObject arg = new JSONObject();
    arg.put("outputfolder", TEMP_OUTPUT_PATH + "/" + "f9a8d471");
    String tempOutputPath = arg.toJSONString();
    String jobArgs = ",\"exec\":\"osm2ogrscript\",\"params\":[{\"input\":\"ToyTestA\"},{\"translation\":\"MGCP.js\"},{\"outputtype\":\"wfs\"},"
            + "{\"removereview\":\"false\"},{\"inputtype\":\"db\"},";
    jobArgs += tempOutputPath + ",";
    jobArgs += "{\"output\":\"f9a8d471\"},{\"outputname\":\"f9a8d471\"}," + "{\"PG_URL\":\"" + pgUrl
            + "\"}],\"exectype\":\"make\"},{\"class\":\"hoot.services.controllers.wfs.WfsManager\","
            + "\"method\":\"createWfsResource\",\"params\":[{\"isprimitivetype\":\"false\",\"value\":\"f9a8d471\","
            + "\"paramtype\":\"java.lang.String\"}],\"exectype\":\"reflection_sync\"}]";

    ExportJobResource spy = Mockito.spy(new ExportJobResource());
    Mockito.doNothing().when((JobControllerBase) spy).postChainJobRquest(anyString(), anyString());
    JobId resp = spy.process(params);//from   w w  w .jav a2s . c  om
    String jobId = resp.getJobid();

    jobArgs = jobArgs.replaceAll("f9a8d471", jobId);
    verify(spy).postChainJobRquest(Matchers.matches(jobId), Matchers.endsWith(jobArgs));
}

From source file:com.conwet.silbops.connectors.comet.CometAPIHandler.java

@SuppressWarnings("unchecked")
public void onRequestGet(AtmosphereResource<HttpServletRequest, HttpServletResponse> event) throws IOException {

    HttpServletResponse res = event.getResponse();
    res.setContentType("text/event-stream;charset=UTF-8");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");

    String stream = getNewStreamId();
    connStatus.addStream(stream, 5, event);

    JSONObject json = new JSONObject();
    json.put("streamID", stream);
    json.put("keepAlivePeriod", keepAlivePeriod);
    PrintWriter writer = res.getWriter();
    writer.println(JSONUtils.sendData("SilboPS.openStream", null, json.toJSONString()));

    event.suspend(Long.MAX_VALUE, true);
}

From source file:com.example.networkPacketFormats.ServeFunction.java

public String getJSONPerformanceString(String sub, String id, int type) {
    System.out.println("I got " + sub + " " + id);
    if (type == 1) {
        /*/*from  w ww .j av a2  s.c  o  m*/
        Last test only
        */
        PreparedStatement p = null;
        try {
            p = (PreparedStatement) con.prepareStatement("select * from student_performance"
                    + " where roll_number='" + id + "' and subject='" + sub + "' order by date desc,time desc");
            ResultSet result = p.executeQuery();

            HashMap<String, String> hm = new HashMap<>();

            if (result.next()) {
                String date = result.getString("date");
                String marks = result.getString("marks");
                String quesAttempted = result.getString("questions_attempted");
                String quesCorrect = result.getString("correct_answers");
                hm.put("date", date);
                hm.put("marks", marks);
                hm.put("quesAttempted", quesAttempted);
                hm.put("correct", quesCorrect);
            }
            /*
            Now form a JSON Object
            */
            JSONObject obj = new JSONObject(hm);
            return obj.toJSONString();
        } catch (SQLException ex) {
            Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (type == 2) {
        /*
        Overall
        */
        PreparedStatement p;
        try {
            ResultSet result;

            p = (PreparedStatement) con.prepareStatement("select * from student_performance"
                    + " where roll_number='" + id + "' " + "order by subject asc");
            result = p.executeQuery();

            HashMap<String, String> hm = new HashMap<>();

            String subject = null;
            String marksStr = "";

            for (int i = 0; result.next(); i++) {
                if (subject == null) {
                    subject = result.getString("subject");
                } else {
                    String tempSubject = result.getString("subject");
                    if (!tempSubject.equals(subject)) {
                        hm.put(subject, marksStr);
                        subject = tempSubject;
                        marksStr = "";
                    }
                }
                marksStr = marksStr + result.getString("marks") + "$";
            }
            hm.put(subject, marksStr);
            /*
            Now form a JSON Object
            */
            JSONObject obj = new JSONObject(hm);
            System.out.println("STRING IS        : " + obj.toJSONString());
            return obj.toJSONString();
        } catch (SQLException ex) {
            Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:me.prokopyl.storagemonitor.beans.JavaBean.java

@Override
public String toJSONString() {
    JSONObject obj = new JSONObject();
    obj.put("BeanType", this.getBeanName());
    Field[] fields = this.getClass().getDeclaredFields();

    for (Field field : fields) {
        if (Modifier.isTransient(field.getModifiers()))
            continue;
        field.setAccessible(true);//from   ww  w  .j  av a  2  s.  co m
        try {
            obj.put(field.getName(), field.get(this));
        } catch (IllegalAccessException ex) {
        }
    }

    return obj.toJSONString();
}

From source file:eg.nileu.cis.nilestore.monitor.server.NsMonitorServer.java

/**
 * Dump grouped viewto json.//from  ww  w. j  av  a  2s .com
 * 
 * @return the string
 */
@SuppressWarnings("unchecked")
private synchronized String dumpGroupedViewtoJSON() {
    List<List<Double>> data = new ArrayList<List<Double>>();
    List<String> nodes = new ArrayList<String>();
    Map<String, String> sslinks = new HashMap<String, String>();

    List<String> legend = new ArrayList<String>();
    legend.add("Used Space");
    legend.add("Count of Shares");
    //

    for (NilestoreAddress peer : view.keySet()) {
        StorageStatusView peerstatus = view.get(peer);
        // if(peerstatus.getUsedSpace() == 0 ||
        // peerstatus.getCountofShares() == 0)
        // continue;

        double size = peerstatus.getUsedSpace() / total_size;
        double number = peerstatus.getCountofShares() / total_count;

        String peerkey = peer.getNickname();
        String peerurl = String.format("http://%s:%s", peer.getPeerAddress().getIp().getHostAddress(),
                peer.getWebPort());

        List<Double> row = new ArrayList<Double>();
        row.add(size);
        row.add(number);

        data.add(row);
        nodes.add(peerkey);
        sslinks.put(peerkey, peerurl);
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    obj.put("nodes", nodes);
    obj.put("sslinks", sslinks);
    obj.put("legend", legend);

    return obj.toJSONString();
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

/**
 * Log in to start session//from  w ww . ja v  a 2 s . co m
 * @param username
 * @param password
 * @return
 * @throws IOException
 * @throws ParseException
 */
@SuppressWarnings("unchecked")
boolean login() {
    try {
        URL url = new URL(host + "rest/user/login");
        HttpURLConnection conn = createConnection(url, "POST", true);

        JSONObject login = new JSONObject();
        login.put("username", user);
        login.put("password", pass);

        OutputStream os = conn.getOutputStream();
        os.write(login.toJSONString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            return false;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(reader);

        session_cookie = obj.get("session_name") + "=" + obj.get("sessid");
        conn.disconnect();
    } catch (Throwable e) {
        throw new OkapiIOException("Error in login().", e);
    }
    return true;
}