Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

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

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private WebViewClient createWebViewClientThatHandlesFileLinksForCharts() {
    WebViewClient webViewClient = new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);//from   ww w  . j  a  va 2  s.  com
            if (uri.getScheme().startsWith("http")) {
                return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues.
            }

            String inputIdStr = uri.getQueryParameter("inputId");
            if (inputIdStr == null) {
                return true;
            }
            long inputId = Long.parseLong(inputIdStr);
            JSONArray results = new JSONArray();
            for (Event event : experiment.getEvents()) {
                JSONArray eventJson = new JSONArray();
                DateTime responseTime = event.getResponseTime();
                if (responseTime == null) {
                    continue; // missed signal;
                }
                eventJson.put(responseTime.getMillis());

                // in this case we are looking for one input from the responses that we are charting.
                for (Output response : event.getResponses()) {
                    if (response.getInputServerId() == inputId) {
                        Input inputById = experiment.getInputById(inputId);
                        if (!inputById.isInvisible() && inputById.isNumeric()) {
                            eventJson.put(response.getDisplayOfAnswer(inputById));
                            results.put(eventJson);
                            continue;
                        }
                    }
                }

            }
            env.put("data", results.toString());
            env.put("inputId", inputIdStr);

            view.loadUrl(stripQuery(url));
            return true;
        }
    };
    return webViewClient;
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private static String convertEventsToJsonString(final Experiment experiment, List<Event> events) {
    // TODO use jackson instead. But preserve these synthesized values for backward compatibility.
    final JSONArray experimentData = new JSONArray();
    for (Event event : events) {
        try {/*from   w w  w .j a  v a2  s .c  o  m*/
            JSONObject eventObject = new JSONObject();
            boolean missed = event.getResponseTime() == null;
            eventObject.put("isMissedSignal", missed);
            if (!missed) {
                eventObject.put("responseTime", event.getResponseTime().getMillis());
            }

            boolean selfReport = event.getScheduledTime() == null;
            eventObject.put("isSelfReport", selfReport);
            if (!selfReport) {
                eventObject.put("scheduleTime", event.getScheduledTime().getMillis());
            }

            JSONArray responses = new JSONArray();
            for (Output response : event.getResponses()) {
                JSONObject responseJson = new JSONObject();
                Input input = experiment.getInputById(response.getInputServerId());
                if (input == null) {
                    continue;
                }
                responseJson.put("inputId", input.getServerId());
                // deprecate inputName in favor of name
                responseJson.put("inputName", input.getName());
                responseJson.put("name", input.getName());
                responseJson.put("responseType", input.getResponseType());
                responseJson.put("isMultiselect", input.isMultiselect());
                responseJson.put("prompt", getTextOfInputForOutput(experiment, response));
                responseJson.put("answer", response.getDisplayOfAnswer(input));
                // deprecated for answerRaw
                responseJson.put("answerOrder", response.getAnswer());
                responseJson.put("answerRaw", response.getAnswer());
                responses.put(responseJson);
            }

            eventObject.put("responses", responses);
            if (responses.length() > 0) {
                experimentData.put(eventObject);
            }
        } catch (JSONException jse) {
            // skip this event and do the next event.
        }
    }
    String experimentDataAsJson = experimentData.toString();
    return experimentDataAsJson;
}

From source file:org.chromium.ChromeBluetooth.java

private void getDevices(CallbackContext callbackContext) throws JSONException {
    JSONArray results = new JSONArray();

    for (BluetoothDevice device : knownBluetoothDevices.values()) {
        results.put(getBasicDeviceInfo(device));
    }//from   w  ww  .  j av  a 2s .c  om

    for (ScanResult result : knownLeScanResults.values()) {
        results.put(getLeDeviceInfo(result));
    }

    callbackContext.success(results);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

public void pubEvent(Channel ch, JSONObject e, FullHttpResponse resp) {
    // Prepare the HTTP request.
    JSONArray es = new JSONArray();
    es.put(e);

    StringWriter estr = new StringWriter();
    es.write(estr);/* ww  w . j a  v  a  2  s.c  o  m*/
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("PUB Event request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.insthub.ecmobile.model.MockServer.java

public static <K> void ajax(AjaxCallback<K> callback) {
    try {/* w  ww . j  av a2 s .c  o  m*/

        JSONObject responseJsonObject = new JSONObject();
        if (callback.getUrl() == ProtocolConst.HOMEDATA) {

            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONObject dataJsonObject = new JSONObject();
            JSONArray itemJsonArray = new JSONArray();
            for (int i = 0; i < 3; i++) {
                PLAYER player = new PLAYER();
                player.description = "";
                player.url = "www.baidu.com";
                player.photo = new PHOTO();

                player.photo.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                itemJsonArray.put(player.toJson());
            }

            dataJsonObject.put("player", itemJsonArray);

            JSONArray item2JsonArray = new JSONArray();
            for (int i = 0; i < 3; i++) {
                SIMPLEGOODS good = new SIMPLEGOODS();
                good.img = new PHOTO();
                good.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                item2JsonArray.put(good.toJson());
            }

            dataJsonObject.put("promote_goods", item2JsonArray);
            responseJsonObject.put("data", dataJsonObject);

        } else if (callback.getUrl() == ProtocolConst.CATEGORYGOODS) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();
            for (int i = 0; i < 3; i++) {
                CATEGORYGOODS good = new CATEGORYGOODS();

                for (int j = 0; j < 3; j++) {
                    SIMPLEGOODS simplegood = new SIMPLEGOODS();
                    simplegood.img = new PHOTO();

                    simplegood.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                    good.goods.add(simplegood);
                }
                good.name = "";
                dataJsonObject.put(good.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);

        } else if (callback.getUrl() == ProtocolConst.SEARCH) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();

            for (int j = 0; j < 3; j++) {
                SIMPLEGOODS simplegood = new SIMPLEGOODS();
                simplegood.img = new PHOTO();

                simplegood.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                dataJsonObject.put(simplegood.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);
        } else if (callback.getUrl() == ProtocolConst.SHOPHELP) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();

            for (int i = 0; i < 3; i++) {
                SHOPHELP shophelp = new SHOPHELP();
                shophelp.name = "??";
                for (int j = 0; j < 3; j++) {
                    ARTICLE article = new ARTICLE();
                    article.short_title = "";
                    article.id = j + "";
                    article.title = "";
                    shophelp.article.add(article);
                }
                dataJsonObject.put(shophelp.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);
        } else if (callback.getUrl() == ProtocolConst.GOODSDETAIL) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONObject dataJsonObject = new JSONObject();
            GOODS goods = new GOODS();

            for (int i = 0; i < 5; i++) {
                PHOTO photo = new PHOTO();
                photo.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                goods.pictures.add(photo);
            }
            responseJsonObject.put("data", goods.toJson());

        }

        ((BeeCallback) callback).callback(callback.getUrl(), responseJsonObject, callback.getStatus());

    } catch (JSONException e) {
        // TODO: handle exception
    }
}

From source file:de.dakror.virtualhub.data.Catalog.java

public JSONObject getJSONObject() {
    try {/* ww w  .j av a 2 s .  co m*/
        JSONObject o = new JSONObject();
        o.put("name", name);
        JSONArray sources = new JSONArray();
        for (File f : this.sources)
            sources.put(f.getPath().replace("\\", "/"));
        o.put("sources", sources);

        o.put("tags", tags.toArray(new String[] {}));

        return o;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

@Override
public String toString() {
    JSONObject jsonObject = null;/*from   www.  java 2s .co m*/
    try {
        if (type == BayeuxMessage.HANDSHAKE_REQ) {
            jsonObject = convertHandshakeReq();
        } else if (type == BayeuxMessage.HANDSHAKE_RESP) {
            jsonObject = convertHandshakeResp();
        } else if (type == BayeuxMessage.CONNECT_REQ) {
            jsonObject = convertConnectReq();
        } else if (type == BayeuxMessage.CONNECT_RESP) {
            jsonObject = convertConnectResp();
        } else if (type == BayeuxMessage.DISCONNECT_REQ) {
            jsonObject = convertDisconnectReq();
        } else if (type == BayeuxMessage.DISCONNECT_RESP) {
            jsonObject = convertDisconnectResp();
        } else if (type == BayeuxMessage.SUBSCRIBE_REQ) {
            jsonObject = convertSubscribeReq();
        } else if (type == BayeuxMessage.SUBSCRIBE_RESP) {
            jsonObject = convertSubscribeResp();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_REQ) {
            jsonObject = convertUnsubscribeReq();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_RESP) {
            jsonObject = convertUnsubscribeResp();
        } else if (type == BayeuxMessage.PUBLISH_REQ) {
            jsonObject = convertPublishReq();
        } else if (type == BayeuxMessage.PUBLISH_RESP) {
            jsonObject = convertPublishResp();
        } else if (type == BayeuxMessage.DELIVER_EVENT) {
            jsonObject = convertDeliverEvent();
        } else {
            throw new JSONException("Invalid BayeuxMessageType " + type);
        }
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json", e);
    }
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(jsonObject);
    String result = null;
    try {
        result = jsonArray.toString(4);
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json array", e);
    }
    return result;
}

From source file:com.jsonstore.util.JSONStoreUtil.java

public static JSONArray convertJSONObjectListToJSONArray(List<JSONObject> objs) {
    JSONArray out = new JSONArray();
    if (objs == null)
        return out;

    for (JSONObject obj : objs) {
        if (obj != null)
            out.put(obj);
    }/*from   w  ww  .  ja va2s  .  com*/

    return out;
}

From source file:com.facebook.internal.BundleJSONConverterTest.java

@Test
public void testUnsupportedValues() throws JSONException {
    Bundle b = new Bundle();
    b.putShort("shortValue", (short) 7);

    boolean exceptionCaught = false;
    try {//from w ww  . j av  a2 s .co m
        BundleJSONConverter.convertToJSON(b);
    } catch (IllegalArgumentException a) {
        exceptionCaught = true;
    }
    assertTrue(exceptionCaught);

    JSONArray jsonArray = new JSONArray();
    jsonArray.put(10);
    JSONObject json = new JSONObject();
    json.put("arrayValue", jsonArray);

    exceptionCaught = false;
    try {
        BundleJSONConverter.convertToBundle(json);
    } catch (IllegalArgumentException a) {
        exceptionCaught = true;
    }
    assertTrue(exceptionCaught);
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Returns the string that represents the selected attributes in a json
 * understandable way. //from   w w w .ja v  a2 s  .  c  o m
 * First tries to search if the json string is passed by the config. If it is
 * not found then we try to create the json string from original LDAP
 * configuration format.  The original format is individual keys for 
 * each value.
 * @return String json parsable string representation of the selected 
 *         attributes 
 */
static String getJsonStringForSelectedAttributes(Map<String, String> config) {
    String schemaValue = config.get(ConfigName.SCHEMAVALUE.toString());
    if (schemaValue == null || schemaValue.equals("[]")) {
        LOG.info("Trying to recover attributes from individual checkboxes");
        StringBuffer schemaKey = new StringBuffer();
        schemaKey.append(ConfigName.SCHEMA.toString()).append("_").append("\\d");
        Pattern keyPattern = Pattern.compile(schemaKey.toString());
        Set<String> configKeySet = config.keySet();
        JSONArray arr = new JSONArray();
        for (String configKey : configKeySet) {
            Matcher matcher = keyPattern.matcher(configKey);
            if (matcher.find()) {
                String schemaAttribute = config.get(configKey);
                if (schemaAttribute != null && schemaAttribute.trim().length() != 0) {
                    arr.put(config.get(configKey));
                }
            }
        }
        if (arr.length() != 0) {
            schemaValue = arr.toString();
        } else {
            schemaValue = "";
        }
    }
    LOG.info("The appended string for selected attributes is: " + schemaValue);
    return schemaValue;
}