Example usage for org.json.simple JSONArray add

List of usage examples for org.json.simple JSONArray add

Introduction

In this page you can find the example usage for org.json.simple JSONArray add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:com.mapr.xml2json.MySaxParser.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);

    String cleanQName = cleanQName(qName);

    if (stk.empty() == true) {
        //System.out.println("Stack empty");
        stk.push(val);
    }//from  w w  w  .j a v  a  2 s.  c o m
    newVal = (JSONObject) stk.pop();
    if (content != null) {

        newVal.put("value", content);
        content = null;
    }

    if (stk.empty() == false) {
        JSONObject parent = (JSONObject) stk.pop();

        if (parent.containsKey(cleanQName) == true) {
            if (parent.get(cleanQName) instanceof JSONObject) {
                JSONObject old_val = (JSONObject) parent.get(cleanQName);
                if (newVal.size() > 0) {
                    JSONArray new_array = new JSONArray();

                    if (old_val.size() == 1 && old_val.containsKey("value") && newVal.size() == 1
                            && newVal.containsKey("value")) {
                        new_array.add(old_val.get("value"));
                        new_array.add(newVal.get("value"));
                    } else {
                        new_array.add(old_val);
                        new_array.add(newVal);
                    }
                    parent.put(cleanQName, new_array);
                }

                stk.push(parent);
            } else if (parent.get(cleanQName) instanceof JSONValue) {
                JSONValue old_val = (JSONValue) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);

            } else if (parent.get(cleanQName) instanceof JSONArray) {
                JSONArray old_val = (JSONArray) parent.get(cleanQName);
                if (newVal.size() == 1 && newVal.containsKey("value")) {
                    old_val.add(newVal.get("value"));
                } else {
                    old_val.add(newVal);
                }
                stk.push(parent);
            } else {
                String old_val = (String) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);
            }
        } else {
            parent.put(cleanQName, newVal);
            stk.push(parent);
        }
    }

}

From source file:com.des.paperbase.ManageData.java

public void insert(String Tablename, Map<String, Object> value) throws IOException, ParseException {
    String data = g.readFileToString(PATH_FILE + "\\" + Tablename + ".json");
    JSONObject table = new JSONObject();
    JSONObject field = new JSONObject();
    JSONArray record = new JSONArray();
    List<String> keySet = g.getKeyFromMap(value);
    if (data.equalsIgnoreCase("{\"data\":[]}")) {
        for (int i = 0; i < keySet.size(); i++) {
            field.put(keySet.get(i), value.get(keySet.get(i)));
        }//from  w  w w. j a  v a 2 s. c o m
        record.add(field);
        table.put("data", record);
        g.writefile(table.toJSONString(), PATH_FILE + "\\" + Tablename + ".json");
    } else {
        JSONObject json = (JSONObject) new JSONParser().parse(data);
        JSONArray OldValue = (JSONArray) json.get("data");
        for (int i = 0; i < keySet.size(); i++) {
            field.put(keySet.get(i), value.get(keySet.get(i)));
        }
        OldValue.add(field);
        json.put("data", OldValue);
        g.writefile(json.toJSONString(), PATH_FILE + "\\" + Tablename + ".json");
    }
}

From source file:getPlayersRanks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww  . j a  va 2 s .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    JSONArray json = new JSONArray();
    DBHandler db = new DBHandler();
    ArrayList<Player> players = db.getPlayers();
    for (int i = 0; i < players.size(); i++) {
        JSONObject JSONplayer = new JSONObject();
        Player player = players.get(i);
        JSONplayer.put("name", player.getName());
        JSONplayer.put("score", player.getScore());
        json.add(JSONplayer);

    }
    response.getWriter().write(json.toString());

}

From source file:fr.zcraft.zlib.components.rawtext.RawTextPart.java

public JSONObject toJSON() {
    JSONObject obj = new JSONObject();
    if (translate) {
        obj.put("translate", text);
    } else {// w ww. j  a  va  2s. co  m
        obj.put("text", text);
    }

    if (!extra.isEmpty()) {
        JSONArray extraArray = new JSONArray();
        for (RawTextPart childPart : this) {
            extraArray.add(childPart.toJSON());
        }
        obj.put("extra", extraArray);
    }

    if (color != null)
        obj.put("color", RawText.toStyleName(color));

    if (bold)
        obj.put("bold", true);
    if (italic)
        obj.put("italic", true);
    if (underline)
        obj.put("underlined", true);
    if (strikethrough)
        obj.put("strikethrough", true);
    if (obfuscated)
        obj.put("obfuscated", true);

    if (actionClick != null && actionClickValue != null)
        obj.put("clickEvent", actionToJSON(actionClick, actionClickValue));

    if (actionHover != null && actionHoverValue != null)
        obj.put("hoverEvent", actionToJSON(actionHover, actionHoverValue));

    return obj;
}

From source file:cz.zeno.miner.stratum.StratumClient.java

@Override
public void submitShare(Work work, byte[] nonce) {
    JSONObject obj = new JSONObject();

    obj.put("id", new Integer(4));
    obj.put("method", "mining.submit");

    //fill params
    JSONArray params = new JSONArray();
    params.add(name);
    params.add(Utils.byteArrayToHexString(work.getJobID()).toLowerCase().replaceFirst("^0+(?!$)", ""));
    params.add(Utils.byteArrayToHexString(work.getExtranonce2()).toLowerCase());
    params.add(Utils.byteArrayToHexString(work.getNtime()).toLowerCase());
    params.add(Utils.byteArrayToHexString(nonce).toLowerCase());

    obj.put("params", params);

    //append to network stream
    try {//  w  w  w .  j  a  v  a2 s.  c  om
        new OutputStreamWriter(outputStream).append(obj.toJSONString() + Constants.NEWLINE).flush();
    } catch (IOException ex) {
        Logger.getLogger(StratumClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    //inform appender (UI, commandline whatever) about submit
    appender.append("submitting nonce: " + Utils.byteArrayToHexString(Utils.swapEndian(nonce)).toLowerCase()
            + Constants.NEWLINE);
}

From source file:azkaban.web.pages.IndexServlet.java

@SuppressWarnings("unchecked")
private JSONObject getJSONDependencyTree(Flow flow) {
    JSONObject jobObject = new JSONObject();
    jobObject.put("name", flow.getName());

    if (flow.hasChildren()) {
        JSONArray dependencies = new JSONArray();
        for (Flow child : flow.getChildren()) {
            JSONObject childObj = getJSONDependencyTree(child);
            dependencies.add(childObj);
        }//from  w  w  w.  jav  a  2 s . c  o  m

        Collections.sort(dependencies, new FlowComparator());
        jobObject.put("dep", dependencies);
    }

    return jobObject;
}

From source file:bizlogic.Records.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st;/*ww w  .j  a  v a 2 s  . com*/
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT userconf.log_list.sensor_id, " + "userconf.log_list.smpl_interval, "
                + "userconf.log_list.running, " + "userconf.log_list.name AS log_name, "
                + "userconf.log_list.log_id, " + "userconf.sensorlist.name AS sensor_name "
                + "FROM USERCONF.LOG_LIST " + "JOIN userconf.sensorlist "
                + "ON userconf.log_list.sensor_id=userconf.sensorlist.sensor_id");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Records.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }

    try {
        FileWriter recordsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/records.json");
        //BufferedWriter recordsFile = new BufferedWriter(_file);
        //recordsFile.write("");
        //recordsFile.flush(); 

        FileReader fr = new FileReader("/var/lib/tomcat8/webapps/ROOT/Records/records.json");
        BufferedReader br = new BufferedReader(fr);

        JSONObject Records = new JSONObject();

        int _total = 0;

        JSONArray recordList = new JSONArray();

        while (rs.next()) {

            String isRunningStr;

            JSONObject sensor_Obj = new JSONObject();

            int sensor_id = rs.getInt("sensor_id");
            sensor_Obj.put("sensor_id", sensor_id);

            String smpl_interval = rs.getString("smpl_interval");
            sensor_Obj.put("smpl_interval", smpl_interval);

            Boolean running = rs.getBoolean("running");
            if (running) {
                //System.out.print("1");
                isRunningStr = "ON";
            } else {
                //System.out.print("0");
                isRunningStr = "OFF";
            }
            sensor_Obj.put("running", isRunningStr);

            String log_name = rs.getString("log_name");
            sensor_Obj.put("log_name", log_name);

            String sensor_name = rs.getString("sensor_name");
            sensor_Obj.put("sensor_name", sensor_name);

            int log_id = rs.getInt("log_id");
            sensor_Obj.put("recid", log_id);

            recordList.add(sensor_Obj);
            _total++;

        }

        rs.close();

        Records.put("total", _total);
        Records.put("records", recordList);

        recordsFile.write(Records.toJSONString());
        recordsFile.flush();

        recordsFile.close();

        System.out.print(Records.toJSONString());
        System.out.print(br.readLine());

    }

    catch (IOException ex) {
        Logger.getLogger(Records.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:modelo.ParametrizacionManagers.TiposContactos.java

/**
* 
* Obtiene la informacion del tipo de contacto mediante un codigo y
* guarda todo en un JSONArray para entregarselo a la vista.
* 
* @return JSONArray/*from   ww w  . j a v a2  s . c  o  m*/
* @throws SQLException 
*/

public JSONArray getTipoContacto(int codigo) throws Exception {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTiposContactos seleccionar = new SeleccionarTiposContactos();
    ResultSet rst = seleccionar.getTipoContacto(codigo);

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();

    while (rst.next()) {
        //Creamos el objecto JSON
        jsonObject.put("descripcion", rst.getString("DESCRIPCION"));
        jsonObject.put("codigo", rst.getString("CODIGO"));

        //Creamos el Array JSON
        jsonArray.add(jsonObject.clone());

    }
    seleccionar.desconectar();
    return jsonArray;

}

From source file:au.edu.ausstage.networks.SearchManager.java

/**
 * A method to take a group of collaborators and output JSON encoded text
 * Unchecked warnings are suppressed due to internal issues with the org.json.simple package
 *
 * @param collaborators the list of collaborators
 * @return              the JSON encoded string
 *//*from  w  ww. j  a v  a  2  s. c  o  m*/
@SuppressWarnings("unchecked")
private String createJSONOutput(LinkedList<Collaborator> collaborators) {

    // assume that all sorting and ordering has already been carried out
    // loop through the list of collaborators and add them to the new JSON objects
    ListIterator iterator = collaborators.listIterator(0);

    // declare helper variables
    JSONArray list = new JSONArray();
    Collaborator collaborator = null;

    while (iterator.hasNext()) {

        // get the collaborator
        collaborator = (Collaborator) iterator.next();

        // add the Json object to the array
        list.add(collaborator.toJsonObject());
    }

    // return the JSON encoded string
    return list.toString();

}

From source file:gov.nih.nci.rembrandt.web.ajax.DynamicListHelper.java

public static String getGeneAliasesList(String commaGenes) {
    //accepts a single gene, or a comma delim list of strings
    JSONArray aliases = new JSONArray();
    commaGenes = commaGenes.replace(" ", "");
    List<String> geneList = Arrays.asList(commaGenes.split(","));
    try {/*w  w  w  .j av a2 s.co  m*/
        Map<String, List<AllGeneAliasLookup>> validMap = DataValidator.searchGeneKeyWordList(geneList);
        if (validMap != null) {
            for (String symbol : geneList) {
                JSONObject a = new JSONObject();
                a.put("original", symbol);

                if (DataValidator.isGeneSymbolFound(symbol)) {
                    //valid, no aliases
                    a.put("status", "valid");
                } else {
                    List<AllGeneAliasLookup> allGeneAliasLookupList = validMap.get(symbol);
                    if (allGeneAliasLookupList != null) {
                        JSONArray ala = new JSONArray();
                        a.put("status", "hasAliases");
                        for (AllGeneAliasLookup allGeneAliasLookup : allGeneAliasLookupList) {
                            JSONObject alo = new JSONObject();
                            alo.put("symbol",
                                    (allGeneAliasLookup.getApprovedSymbol() != null)
                                            ? allGeneAliasLookup.getApprovedSymbol()
                                            : "N/A");
                            alo.put("name",
                                    (allGeneAliasLookup.getApprovedName() != null)
                                            ? allGeneAliasLookup.getApprovedName()
                                            : "N/A");
                            alo.put("alias",
                                    (allGeneAliasLookup.getAlias() != null) ? allGeneAliasLookup.getAlias()
                                            : "N/A");
                            ala.add(alo);
                        }
                        a.put("aliases", ala);
                    } else { //no symbol found
                        a.put("status", "invalid");
                        //                     System.out.println("Symbol:"+symbol+"\t"+ "Invalid symbol or not in the database."+"\n");   
                    }
                }
                aliases.add(a);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return aliases.toString();
}