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.facebook.android.friendsmash.integration.GraphAPICall.java

/**
 * Adds data from specified GraphResponse to stored graphResponse variable. This is used to
 * combine the data from multiple pages into single GraphResponse object.
 * See https://developers.facebook.com/docs/graph-api/using-graph-api/#paging for more details
 * on paging.//w w  w. jav a2 s  .  c  o m
 */
private void addDataToResponse(GraphResponse response) {
    if (graphResponse == null) {
        graphResponse = response;
    } else {
        JSONArray newData = response.getJSONObject().optJSONArray("data");
        JSONArray existingData = graphResponse.getJSONObject().optJSONArray("data");
        for (int i = 0; i < newData.length(); i++) {
            existingData.put(newData.opt(i));
        }
    }
}

From source file:com.connectsdk.cordova.ConnectSDKCordova.java

public void sendEvent(CallbackContext callbackContext, String event, Object... objs) {
    if (callbackContext != null) {
        PluginResult result;/*from   w  w  w . j av a2s. com*/

        JSONArray arr = new JSONArray();
        arr.put(event);

        for (Object obj : objs) {
            arr.put(obj);
        }

        result = new PluginResult(PluginResult.Status.OK, arr);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
    }
}

From source file:cz.vse.fis.keg.entityclassifier.exporter.JSONExporter.java

public String toJSONOneEntity(List<Entity> entities) {
    String jsonResult = "";
    try {//from w  ww  .  jav a2s .  com

        JSONObject jsonE = new JSONObject();
        if (!entities.isEmpty()) {

            Entity e = entities.get(0);

            jsonE.put("underlyingString", e.getUnderlyingString());
            ArrayList<Type> types = e.getTypes();

            JSONArray typesJ = new JSONArray();

            if (types != null) {
                for (Type t : types) {

                    JSONObject typeJ = new JSONObject();

                    String tLabel = t.getTypeLabel();
                    if (tLabel != null) {
                        typeJ.put("typeLabel", t.getTypeLabel());
                    } else {
                        typeJ.put("typeLabel", JSONObject.NULL);
                    }

                    String tURI = t.getTypeURI();
                    if (tURI != null) {
                        typeJ.put("typeURI", t.getTypeURI());
                    } else {
                        typeJ.put("typeURI", JSONObject.NULL);
                    }

                    typeJ.put("entityLabel", t.getEntityLabel());
                    typeJ.put("entityURI", t.getEntityURI());

                    Confidence classificationConf = t.getClassificationConfidence();

                    if (classificationConf != null) {

                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", classificationConf.getValue());

                        if (classificationConf.getType() != null) {
                            confValueJ.put("type", classificationConf.getType());
                        } else {
                            confValueJ.put("type", "classification");
                        }
                        typeJ.put("classificationConfidence", confValueJ);
                    } else {
                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", -1);
                        confValueJ.put("type", "classification");
                        typeJ.put("classificationConfidence", confValueJ);
                    }

                    typeJ.put("provenance", t.getProvenance());
                    typesJ.put(typeJ);
                }
                jsonE.put("types", typesJ);
            }
        }

        jsonResult = jsonE.toString();
        return jsonResult;

    } catch (Exception ex) {
        Logger.getLogger(JSONExporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }
    return "problem";
}

From source file:cz.vse.fis.keg.entityclassifier.exporter.JSONExporter.java

public String toJSON(List<Entity> entities) {
    String jsonResult = "";
    try {/*www  .  j  av  a 2s . c  om*/

        JSONArray jsonEntities = new JSONArray();

        for (Entity e : entities) {

            JSONObject jsonE = new JSONObject();
            jsonE.put("entityType", e.getEntityType());
            jsonE.put("underlyingString", e.getUnderlyingString());
            jsonE.put("startOffset", e.getStartOffset());
            jsonE.put("endOffset", e.getEndOffset());
            ArrayList<Type> types = e.getTypes();

            JSONArray typesJ = new JSONArray();

            if (types != null) {
                for (Type t : types) {

                    JSONObject typeJ = new JSONObject();

                    String tLabel = t.getTypeLabel();
                    if (tLabel != null) {
                        typeJ.put("typeLabel", t.getTypeLabel());
                    } else {
                        String tmp = null;
                        typeJ.put("typeLabel", JSONObject.NULL);
                    }

                    String tURI = t.getTypeURI();
                    if (tURI != null) {
                        typeJ.put("typeURI", t.getTypeURI());
                    } else {
                        String tmp = null;
                        typeJ.put("typeURI", JSONObject.NULL);
                    }

                    typeJ.put("entityLabel", t.getEntityLabel());
                    typeJ.put("entityURI", t.getEntityURI());

                    Confidence classificationConf = t.getClassificationConfidence();

                    if (classificationConf != null) {

                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", classificationConf.getValue());

                        if (classificationConf.getType() != null) {
                            confValueJ.put("type", classificationConf.getType());
                        } else {
                            confValueJ.put("type", "classification");
                        }
                        typeJ.put("classificationConfidence", confValueJ);
                    } else {
                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", -1);
                        confValueJ.put("type", "classification");
                        typeJ.put("classificationConfidence", confValueJ);
                    }

                    // create element linking confidence
                    Confidence linkingConf = t.getLinkingConfidence();
                    if (linkingConf != null) {
                        JSONObject linkValueJ = new JSONObject();
                        linkValueJ.put("value", linkingConf.getValue());
                        if (linkingConf.getType() != null) {
                            linkValueJ.put("type", linkingConf.getType());
                        }
                        typeJ.put("linkingConfidence", linkValueJ);
                    } else {
                        JSONObject linkValueJ = new JSONObject();
                        linkValueJ.put("value", -1);
                        linkValueJ.put("type", "linking");
                        typeJ.put("linkingConfidence", linkValueJ);
                    }

                    Salience s = t.getSalience();
                    if (s != null) {
                        JSONObject salienceJ = new JSONObject();
                        salienceJ.put("score", s.getScore());
                        salienceJ.put("confidence", s.getConfidence());
                        salienceJ.put("classLabel", s.getClassLabel());
                        typeJ.put("salience", salienceJ);
                    }

                    typeJ.put("provenance", t.getProvenance());
                    typesJ.put(typeJ);
                }
                jsonE.put("types", typesJ);
            }
            jsonEntities.put(jsonE);
        }

        jsonResult = jsonEntities.toString();
        return jsonResult;

    } catch (Exception ex) {
        Logger.getLogger(JSONExporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }
    return "problem";
}

From source file:nl.b3p.viewer.stripes.IbisAttributeListActionBean.java

/**
 * Convert a SimpleFeatureCollection to JSON with metadata.
 *
 * @param sfc collections of features/*w  ww. j a  v  a 2 s  .  c om*/
 * @param json output/appendend to json structure
 * @param featureTypeAttributes flamingo attribute descriptors for the
 * features
 * @param outputPropNames fieldnames to put in output
 * @throws JSONException is any
 */
private void featuresToJson(SimpleFeatureCollection sfc, JSONObject json,
        List<AttributeDescriptor> featureTypeAttributes, List<String> outputPropNames) throws JSONException {

    // metadata for fData fields
    JSONArray fields = new JSONArray();
    // columns for grid
    JSONArray columns = new JSONArray();
    // fData payload
    JSONArray datas = new JSONArray();

    SimpleFeatureIterator sfIter = sfc.features();

    boolean getMetadataFromFirstFeature = true;
    while (sfIter.hasNext()) {
        SimpleFeature feature = sfIter.next();
        JSONObject fData = new JSONObject();

        for (AttributeDescriptor attr : featureTypeAttributes) {
            String name = attr.getName();
            if (getMetadataFromFirstFeature) {
                if (outputPropNames.contains(name)) {
                    // only load metadata into json this for first feature
                    JSONObject field = new JSONObject().put("name", name).put("type", attr.getExtJSType());
                    if (reportType == ReportType.ISSUE
                            && attr.getType().equals(AttributeDescriptor.TYPE_DATE)) {
                        field.put("dateFormat", "Y-m");
                    }
                    fields.put(field);
                    columns.put(new JSONObject().put("text", (attr.getAlias() != null ? attr.getAlias() : name))
                            .put("dataIndex", name));
                }
            }
            fData.put(attr.getName(), feature.getAttribute(attr.getName()));
        }
        datas.put(fData);
        getMetadataFromFirstFeature = false;
    }

    json.getJSONObject(JSON_METADATA).put("fields", fields);
    json.getJSONObject(JSON_METADATA).put("columns", columns);
    json.put("data", datas);
    json.put("total", datas.length());

    sfIter.close();
}

From source file:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

/**
 * Executes the request and returns a boolean.
 *
 * @param action          The action to execute.
 * @param argsArray       JSONArray of arguments for the plugin.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return boolean.//from www  .java 2s  .c  o m
 */
public boolean execute(String action, JSONArray argsArray, CallbackContext callbackContext)
        throws JSONException {
    JSONObject args;
    JSONObject options;
    if (argsArray.length() > 0) {
        args = argsArray.getJSONObject(0);
        options = args.getJSONObject(Args.OPTIONS);
    } else {
        //no arguments passed, initialize with empty JSON Objects
        args = new JSONObject();
        options = new JSONObject();
    }

    if (action.equals(Actions.VIEW_DOCUMENT)) {
        String url = args.getString(Args.URL);
        String contentType = args.getString(Args.CONTENT_TYPE);

        JSONObject androidOptions = options.getJSONObject(ANDROID_OPTIONS);

        String packageId = androidOptions.getString(Options.VIEWER_APP_PACKAGE_ID);
        String activity = androidOptions.getString(Options.VIEWER_APP_ACTIVITY);
        //put cordova arguments into Android Bundle in order to pass them to the external Activity
        Bundle viewerOptions = new Bundle();
        //exec
        viewerOptions.putString(DOCUMENTVIEW_OPTIONS + "." + Options.CLOSE_LABEL,
                options.getJSONObject(DOCUMENTVIEW_OPTIONS).getString(Options.CLOSE_LABEL));
        viewerOptions.putString(NAVIGATIONVIEW_OPTIONS + "." + Options.CLOSE_LABEL,
                options.getJSONObject(NAVIGATIONVIEW_OPTIONS).getString(Options.CLOSE_LABEL));
        viewerOptions.putBoolean(EMAIL_OPTIONS + "." + Options.ENABLED,
                options.getJSONObject(EMAIL_OPTIONS).getBoolean(Options.ENABLED));
        viewerOptions.putBoolean(PRINT_OPTIONS + "." + Options.ENABLED,
                options.getJSONObject(PRINT_OPTIONS).getBoolean(Options.ENABLED));
        viewerOptions.putBoolean(OPENWITH_OPTIONS + "." + Options.ENABLED,
                options.getJSONObject(OPENWITH_OPTIONS).getBoolean(Options.ENABLED));
        viewerOptions.putBoolean(BOOKMARKS_OPTIONS + "." + Options.ENABLED,
                options.getJSONObject(BOOKMARKS_OPTIONS).getBoolean(Options.ENABLED));
        viewerOptions.putBoolean(SEARCH_OPTIONS + "." + Options.ENABLED,
                options.getJSONObject(SEARCH_OPTIONS).getBoolean(Options.ENABLED));
        viewerOptions.putString(TITLE_OPTIONS, options.getString(TITLE_OPTIONS));

        this._open(url, contentType, packageId, activity, callbackContext, viewerOptions);
    } else if (action.equals(Actions.INSTALL_VIEWER_APP)) {
        String packageId = options.getJSONObject(ANDROID_OPTIONS).getString(Options.VIEWER_APP_PACKAGE_ID);

        this._install(packageId, callbackContext);
    } else if (action.equals(Actions.CAN_VIEW)) {
        String url = args.getString(Args.URL);

        String contentType = args.getString(Args.CONTENT_TYPE);

        JSONObject androidOptions = options.getJSONObject(ANDROID_OPTIONS);

        String packageId = androidOptions.getString(Options.VIEWER_APP_PACKAGE_ID);

        JSONObject successObj = null;
        if (PDF.equals(contentType)) {
            if (canGetFile(url)) {
                if (!this._appIsInstalled(packageId)) {
                    successObj = new JSONObject();
                    successObj.put(Result.STATUS, PluginResult.Status.NO_RESULT.ordinal());
                    successObj.put(Result.MISSING_APP_ID, packageId);
                } else {
                    successObj = new JSONObject();
                    successObj.put(Result.STATUS, PluginResult.Status.OK.ordinal());
                }
            } else {
                Log.d(TAG, "File " + url + " not available");
            }
        }

        if (successObj == null) {
            successObj = new JSONObject();
            successObj.put(Result.STATUS, PluginResult.Status.NO_RESULT.ordinal());
        }

        callbackContext.success(successObj);
    } else if (action.equals(Actions.GET_SUPPORT_INFO)) {
        JSONObject successObj = new JSONObject();
        JSONArray supported = new JSONArray();
        supported.put(PDF);
        successObj.put(Result.SUPPORTED, supported);
        callbackContext.success(successObj);
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put(Result.STATUS, PluginResult.Status.INVALID_ACTION.ordinal());
        errorObj.put(Result.MESSAGE, "Invalid action '" + action + "'");
        callbackContext.error(errorObj);
    }
    return true;
}

From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java

@Override
public List<LocationResult> getLocations(String input) {
    String language = getLanguage();
    String params = "\"" + input + "\" and lang = \"" + language + "\"";
    String url = URL_LOCATION + Uri.encode(params);
    JSONObject jsonResults = fetchResults(url);
    if (jsonResults == null) {
        return null;
    }// ww  w .  j  av  a 2  s.  c  om

    try {
        JSONArray places = jsonResults.optJSONArray("place");
        if (places == null) {
            // Yahoo returns an object instead of an array when there's only one result
            places = new JSONArray();
            places.put(jsonResults.getJSONObject("place"));
        }

        ArrayList<LocationResult> results = new ArrayList<LocationResult>();
        for (int i = 0; i < places.length(); i++) {
            LocationResult result = parsePlace(places.getJSONObject(i));
            if (result != null) {
                results.add(result);
            }
        }
        return results;
    } catch (JSONException e) {
        Log.e(TAG, "Received malformed places data (input=" + input + ", lang=" + language + ")", e);
    }
    return null;
}

From source file:org.marietjedroid.connect.MarietjeMessenger.java

/**
 * Sends a request and handles the response
 * /* w  w w . ja v a 2s . c  o  m*/
 * @param list
 * @throws MarietjeException
 */
private void doRequest(List<JSONObject> list) throws MarietjeException {
    if (list != null)
        list = new ArrayList<JSONObject>(list);
    else
        list = new ArrayList<JSONObject>();

    HttpClient httpClient = new DefaultHttpClient();
    if (this.token == null) {
        throw new IllegalStateException("token is null");
    }

    JSONArray json = new JSONArray();
    json.put(token);
    for (JSONObject m : list)
        json.put(m);
    HttpGet hp = null;
    try {
        System.out.println("JSON: " + json.toString());
        String url = String.format("http://%s:%s%s?m=%s", host, port, path,
                URLEncoder.encode(json.toString(), "UTF-8"));
        System.out.println("url: " + url);
        hp = new HttpGet(url);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    StringBuilder sb = new StringBuilder();
    try {
        HttpResponse r = httpClient.execute(hp);
        InputStreamReader is = new InputStreamReader(r.getEntity().getContent());
        BufferedReader br = new BufferedReader(is);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("response: " + line);
            sb.append(line);
        }
    } catch (IOException e) {
        MarietjeException tr = new MarietjeException("Connection stuk!" + e.getMessage());
        this.exception = tr;
        throw tr;
    }

    JSONArray d = null;
    try {
        d = new JSONArray(new JSONTokener(sb.toString()));
    } catch (JSONException e) {
        throw (exception = new MarietjeException("Ja, JSON kapot!"));
    }

    if (d == null || d.length() != 3)
        throw (exception = new MarietjeException("Unexpected length of response list"));
    String token = null;
    JSONArray msgs = null;
    try {
        token = d.getString(0);
        msgs = d.getJSONArray(1);
        // JSONArray stream = d.getJSONArray(2);
    } catch (JSONException e) {
        throw (exception = new MarietjeException("unexpected format of response list"));
    }

    synchronized (this.outSemaphore) {
        String oldToken = this.token;
        this.token = token;

        if (oldToken == null) {
            this.outSemaphore.release();
        }
    }

    for (int i = 0; i < msgs.length(); i++) {
        try {
            System.out.println("adding msg to queue");
            synchronized (queueMessageIn) {
                this.queueMessageIn.add(msgs.getJSONObject(i));
            }
            this.messageInSemaphore.release();
        } catch (JSONException e) {
            System.err.println("ontvangen json kapot");
            e.printStackTrace();
        }
    }

    // TODO Streams left out.

}

From source file:com.facebook.stream.StreamJsHandler.java

/**
 * Renders the html for the new status./* ww w  .j  a v  a2 s .c o m*/
 * 
 * @param response
 * @param message
 * @return
 * @throws JSONException
 */
private String renderStatus(JSONObject response, String message) throws JSONException {

    String postId = response.getString("id");
    JSONObject post = new JSONObject();
    post.put("id", postId);
    post.put("message", message);

    JSONObject from = createAuthorObj();
    post.put("from", from);

    JSONArray actions = new JSONArray();
    JSONObject like = new JSONObject();
    like.put("name", "Like");
    actions.put(like);

    JSONObject comment = new JSONObject();
    comment.put("name", "Comment");
    actions.put(comment);

    post.put("actions", actions);

    SimpleDateFormat format = StreamRenderer.getDateFormat();
    String timestamp = format.format(new Date());
    post.put("created_time", timestamp);

    String html = StreamRenderer.renderSinglePost(post);
    return html;
}

From source file:com.adf.bean.AbsBean.java

private JSONArray arrayObjectToJson(Object val) {
    int count = Array.getLength(val);
    JSONArray arr = new JSONArray();
    for (int i = 0; i < count; i++) {
        Object obj = Array.get(val, i);
        arr.put(obj);
    }/*ww w.  ja va  2  s . c o m*/
    return arr;
}