Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

/**
 * This method looks recursively for arrays and encapsulates each of them into another array. 
 * So, anything like this:<br/>//from   www  .  ja  v a  2 s  .  c  om
 * <code>
 * {"myKey":["stuff1","stuff2"]}
 * </code><br/>
 * would become this:<br/>
 * <code>
 * {"myKey":[["stuff1","stuff2"]]}
 * </code><br/>
 * We do this strange preprocessing because structures like the first example are  
 * converted to XML producing this result:<br/>
 * <code>
 * &lt;myKey&gt;stuff1&lt;/myKey&gt;&lt;myKey&gt;stuff2&lt;/myKey&gt;
 * </code><br/>
 * Which makes impossible to distinguish single-element arrays from an element 
 * outside any array, because, both this:
 * <code>
 * {"singleElement":["stuff"]}
 * </code><br/>
 * and this:<br/>
 * <code>
 * {"singleElement":"stuff"}
 * </code><br/>
 * Would be converted to:<br/>
 * <code>
 * &lt;singleElement&gt;stuff&lt;/singleElement&gt;
 * </code><br/>
 * By doing this, we allow distingushing a single-element array from an non-array element, because 
 * the first one would be converted to:<br/>
 * <code>
 * &lt;singleElement&gt;&lt;array&gt;stuff&lt;/array&gt;&lt;/singleElement&gt;
 * 
 * @param jsonRoot The {@link JSONObject} or {@link JSONArray} which is the root of our JSON document.
 */
private void encapsulateArraysAtJSONRecursive(Object jsonRoot) {
    if (jsonRoot instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) jsonRoot;
        Set<String> keys = ImmutableSet.copyOf(jsonObject.keySet());
        for (String key : keys) {
            Object value = jsonObject.get(key);
            encapsulateArraysAtJSONRecursive(value);
            if (value instanceof JSONArray) {
                JSONArray encapsulatingJsonArray = new JSONArray();
                encapsulatingJsonArray.put(0, value);
                jsonObject.put(key, encapsulatingJsonArray);
            }
        }
    } else if (jsonRoot instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) jsonRoot;
        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.get(i);
            encapsulateArraysAtJSONRecursive(value);
            if (value instanceof JSONArray) {
                JSONObject encapsulatingJsonObject = new JSONObject();
                encapsulatingJsonObject.put(XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, value);
                jsonArray.put(i, encapsulatingJsonObject);
            }
        }
    } else {
        return;
    }
}

From source file:com.intel.iotkitlib.LibModules.AggregatedReportInterface.java

public String createBodyForAggregatedReportInterface() throws JSONException {
    JSONObject reportInterfaceJson = new JSONObject();
    if (this.msgType == null) {
        reportInterfaceJson.put("msgType", "aggregatedReportRequest");
    } else {//from   w ww .  jav  a  2s.  c o  m
        reportInterfaceJson.put("msgType", this.msgType);
    }
    reportInterfaceJson.put("offset", this.offset);
    reportInterfaceJson.put("limit", this.limit);
    if (this.countOnly) {
        reportInterfaceJson.put("countOnly", this.countOnly);
    }
    if (this.outputType != null) {
        reportInterfaceJson.put("outputType", this.outputType);
    }
    if (this.aggregationMethods != null) {
        JSONArray aggregationArray = new JSONArray();
        for (String aggregationMethod : this.aggregationMethods) {
            aggregationArray.put(aggregationMethod);
        }
        reportInterfaceJson.put("aggregationMethods", aggregationArray);
    }
    if (this.dimensions != null) {
        JSONArray dimensionArray = new JSONArray();
        for (String dimension : this.dimensions) {
            dimensionArray.put(dimension);
        }
        reportInterfaceJson.put("dimensions", dimensionArray);
    }
    if (this.gatewayIds != null) {
        JSONArray gatewayArray = new JSONArray();
        for (String gatewayId : this.gatewayIds) {
            gatewayArray.put(gatewayId);
        }
        reportInterfaceJson.put("gatewayIds", gatewayArray);
    }
    if (this.deviceIds != null) {
        JSONArray deviceIdArray = new JSONArray();
        for (String deviceId : this.deviceIds) {
            deviceIdArray.put(deviceId);
        }
        reportInterfaceJson.put("deviceIds", deviceIdArray);
    }
    if (this.componentIds != null) {
        JSONArray componentIdArray = new JSONArray();
        for (String componentId : this.componentIds) {
            componentIdArray.put(componentId);
        }
        reportInterfaceJson.put("componentIds", componentIdArray);
    }
    reportInterfaceJson.put("startTimestamp", this.startTimestamp);
    reportInterfaceJson.put("endTimestamp", this.endTimestamp);
    //sort
    if (this.sort != null) {
        JSONArray sortArray = new JSONArray();
        for (NameValuePair nameValuePair : this.sort) {
            JSONObject nameValueJson = new JSONObject();
            nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue());
            sortArray.put(nameValueJson);
        }
        reportInterfaceJson.put("sort", sortArray);
    }
    if (this.filters != null) {
        JSONObject filterJson = new JSONObject();
        for (AttributeFilter attributeFilter : this.filters.filterData) {
            JSONArray filterValuesArray = new JSONArray();
            for (String filterValue : attributeFilter.filterValues) {
                filterValuesArray.put(filterValue);
            }
            filterJson.put(attributeFilter.filterName, filterValuesArray);
        }
        reportInterfaceJson.put("filters", filterJson);
    }
    return reportInterfaceJson.toString();
}

From source file:org.loklak.api.server.AppsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post post = RemoteAccess.evaluate(request);

    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    post.setResponse(response, "application/javascript");

    // generate json
    File apps = new File(DAO.html_dir, "apps");
    JSONObject json = new JSONObject(true);
    JSONArray app_array = new JSONArray();
    json.put("apps", app_array);
    for (String appname : apps.list())
        try {//from   ww  w. j av  a2s  .  co  m
            File apppath = new File(apps, appname);
            if (!apppath.isDirectory())
                continue;
            Set<String> files = new HashSet<>();
            for (String f : apppath.list())
                files.add(f);
            if (!files.contains("index.html"))
                continue;
            if (!files.contains("app.json"))
                continue;
            File json_ld_file = new File(apppath, "app.json");
            Map<String, Object> json_ld_map = DAO.jsonMapper.readValue(json_ld_file, DAO.jsonTypeRef);
            JSONObject json_ld = new JSONObject(json_ld_map);
            app_array.put(json_ld);
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }

    // write json
    response.setCharacterEncoding("UTF-8");
    FileHandler.setCaching(response, 60);
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();

    post.finalize();
}

From source file:org.uiautomation.ios.server.command.web.FindElementsHandler.java

@Override
public Response handle() throws Exception {
    JSONObject payload = getRequest().getPayload();

    String type = payload.getString("using");
    String value = payload.getString("value");

    RemoteWebElement element = null;/*from w  ww.j ava  2s  .c  om*/

    if (getRequest().hasVariable(":reference")) {
        int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
        element = new RemoteWebElement(new NodeId(id), getSession());
    } else {
        element = getSession().getWebInspector().getDocument();
    }

    List<RemoteWebElement> res;
    if ("link text".equals(type)) {
        res = element.findElementsByLinkText(value, false);
    } else if ("partial link text".equals(type)) {
        res = element.findElementsByLinkText(value, true);
    } else if ("xpath".equals(type)) {
        res = element.findElementsByXpath(value);
    } else {
        String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value);
        res = element.findElementsByCSSSelector(cssSelector);
    }

    JSONArray array = new JSONArray();

    List<JSONObject> list = new ArrayList<JSONObject>();
    for (RemoteWebElement el : res) {
        list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId()));
    }

    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);
    resp.setValue(list);
    return resp;
}

From source file:com.facebook.share.ShareApi.java

private void stageArrayList(final ArrayList arrayList,
        final CollectionMapper.OnMapValueCompleteListener onArrayListStagedListener) {
    final JSONArray stagedObject = new JSONArray();
    final CollectionMapper.Collection<Integer> collection = new CollectionMapper.Collection<Integer>() {
        @Override//from  w w w . ja v  a 2s. c  o m
        public Iterator<Integer> keyIterator() {
            final int size = arrayList.size();
            final Mutable<Integer> current = new Mutable<Integer>(0);
            return new Iterator<Integer>() {
                @Override
                public boolean hasNext() {
                    return current.value < size;
                }

                @Override
                public Integer next() {
                    return current.value++;
                }

                @Override
                public void remove() {
                }
            };
        }

        @Override
        public Object get(Integer key) {
            return arrayList.get(key);
        }

        @Override
        public void set(Integer key, Object value, CollectionMapper.OnErrorListener onErrorListener) {
            try {
                stagedObject.put(key, value);
            } catch (final JSONException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging object.";
                }
                onErrorListener.onError(new FacebookException(message));
            }
        }
    };
    final CollectionMapper.OnMapperCompleteListener onStagedArrayMapperCompleteListener = new CollectionMapper.OnMapperCompleteListener() {
        @Override
        public void onComplete() {
            onArrayListStagedListener.onComplete(stagedObject);
        }

        @Override
        public void onError(FacebookException exception) {
            onArrayListStagedListener.onError(exception);
        }
    };
    stageCollectionValues(collection, onStagedArrayMapperCompleteListener);
}

From source file:com.mobage.air.extension.social.kr.Textdata_getEntries.java

@Override
public FREObject call(final FREContext context, FREObject[] args) {
    try {//  w w w .j  a v a2s .c om
        ArgsParser a = new ArgsParser(args);
        final String groupName = a.nextString();
        final ArrayList<String> entryIds = a.nextStringArrayList();
        final String onSuccessId = a.nextString();
        final String onErrorId = a.nextString();
        a.finish();

        com.mobage.android.social.kr.Textdata.OnGetEntriesComplete cb = new com.mobage.android.social.kr.Textdata.OnGetEntriesComplete() {
            @Override
            public void onSuccess(ArrayList<com.mobage.android.social.kr.Textdata.TextdataEntry> entries) {
                try {
                    JSONArray args = new JSONArray();
                    JSONArray jsonEntries = new JSONArray();
                    for (com.mobage.android.social.kr.Textdata.TextdataEntry entry : entries) {
                        jsonEntries.put(Convert.krTextdataEntryToJSON(entry));
                    }
                    args.put(jsonEntries);
                    Dispatcher.dispatch(context, onSuccessId, args);
                } catch (Exception e) {
                    Dispatcher.exception(context, e);
                }
            }

            @Override
            public void onError(Error error) {
                Dispatcher.dispatch(context, onErrorId, error);
            }
        };

        com.mobage.android.social.kr.Textdata.getEntries(groupName, entryIds, cb);
    } catch (Exception e) {
        Dispatcher.exception(context, e);
    }
    return null;
}

From source file:com.util.httpRecargas.java

public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) {

    //   System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/* w w w  .  j  a v a 2  s  . co  m*/
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje);
    //   System.out.println(" el objeto jdata es " + jdata);
    objJason = new JSONObject(jdata);
    // System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());
    /*
            List<String> list = new ArrayList<String>();
            for (int i = 0; i
        < jsonArray.length(); i++) {
    list.add(String.valueOf(i));
    list.add(jsonArray.getJSONObject(i).getString("created_date"));
    list.add(jsonArray.getJSONObject(i).getString("description"));
    list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
    list.add(jsonArray.getJSONObject(i).getString("before_balance"));
    list.add(jsonArray.getJSONObject(i).getString("after_balance"));
            }
            System.out.println("\n\nel array java contiene "+ list.toString());
    */
    List<Recarga> recargas = new ArrayList<Recarga>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Recarga recarga = new Recarga();
        recarga.setNo(i);
        recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date"));
        recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description"));
        recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
        recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance"));
        recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance"));

        recargas.add(recarga);
    }

    for (int i = 0; i < recargas.size(); i++) {
        System.out.print("\n\nNo" + recargas.get(i).getNo());
        System.out.print("\nFecna " + recargas.get(i).getFecha());
        System.out.print("\nDescripcion " + recargas.get(i).getDescripcion());
        System.out.print("\nMonto " + recargas.get(i).getMonto());
        System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior());
        System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior());

    }
    return recargas;

}

From source file:com.watabou.pixeldungeon.utils.Bundle.java

public void put(String key, int[] array) {
    try {// w w  w  . j  a  v a2 s .co  m
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < array.length; i++) {
            jsonArray.put(i, array[i]);
        }
        data.put(key, jsonArray);
    } catch (JSONException e) {

    }
}

From source file:com.watabou.pixeldungeon.utils.Bundle.java

public void put(String key, boolean[] array) {
    try {/*  ww w . ja  v a 2s  .  c  o  m*/
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < array.length; i++) {
            jsonArray.put(i, array[i]);
        }
        data.put(key, jsonArray);
    } catch (JSONException e) {

    }
}

From source file:com.watabou.pixeldungeon.utils.Bundle.java

public void put(String key, String[] array) {
    try {//w  ww  . j  a va 2 s  .co  m
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < array.length; i++) {
            jsonArray.put(i, array[i]);
        }
        data.put(key, jsonArray);
    } catch (JSONException e) {

    }
}