Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.jppf.example.matrix.JwebSockClient.java

public void doMatrixMultiplication(JSONArray matrixA, JSONArray matrixB, String id) {
    String[] packetData = new String[3]; //[0] == ID, [1] == matrixStringA [2] =matrixB
    String matrixa = matrixA.toJSONString();
    String matrixb = matrixB.toJSONString();
    System.out.println("05");
    packetData[0] = id;/*from   w w w. jav  a2s  .c  o  m*/
    packetData[1] = matrixa;
    packetData[2] = matrixb;
    String[] resultData = new String[2];
    System.out.println("01");
    MatrixRunner runner = new MatrixRunner();
    System.out.println("012a");
    resultData = runner.go(packetData);
    System.out.println("012b");
    if (resultData != null) {
        System.out.println(resultData.length);
    } else
        System.out.println("array is null");

    if (resultData[0] == null) {
        System.out.println("result0: null");
    }

    //System.out.println("result0: "+resultData[0]);
    System.out.println("result1: " + resultData[1]);
    sendProcessedMatrix(resultData);
}

From source file:org.jppf.example.matrix.Matrix.java

public String printConsole() {
    JSONArray list = new JSONArray();
    for (int i = 0; i < rows; i++) {
        JSONObject obj = new JSONObject();
        for (int j = 0; j < cols; j++) {
            obj.put(String.valueOf(j), values[i][j]);
        }/*from  www  . j  a v a  2  s.  co  m*/
        list.add(obj);
    }
    return list.toJSONString();
}

From source file:org.jumpmind.metl.core.runtime.component.AbstractRdbmsComponentRuntime.java

@SuppressWarnings("unchecked")
protected ArrayList<String> convertResultsToTextPayload(List<Result> results) {
    ArrayList<String> payload = new ArrayList<String>();
    JSONArray jsonResults = new JSONArray();
    for (Result result : results) {
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("Sql", result.sql);
        jsonResult.put("Rows Affected", result.numberRowsAffected);
        jsonResults.add(jsonResult);/*www  .  j a  va2 s  .com*/
    }
    payload.add(jsonResults.toJSONString());
    return payload;
}

From source file:org.kawanfw.sql.json.ObjectArrayTransport.java

/**
 * Format for JSON String a string array
 * /*from w w  w  .  ja  v a2s  . c o  m*/
 * @param StringArray
 *            a string array
 * 
 * @return the formated JSON string ready for transport
 */

@SuppressWarnings("unchecked")
public static String toJson(Object[] objectArray) {

    JSONArray jsonArray = new JSONArray();

    for (int i = 0; i < objectArray.length; i++) {
        jsonArray.add(objectArray[i]);
    }

    String jsonString = jsonArray.toJSONString();
    debug("jsonString: " + jsonString);
    return jsonString;
}

From source file:org.lavajug.streamcaster.plugins.AnnotationPluginManager.java

/**
 * return a JSON representation of the plugin configuration
 *
 * @param name of the plugin/*from  w ww .j ava  2  s  .  c  o m*/
 * @return JSON representation of the plugin configuration
 */
@Override
@SuppressWarnings("unchecked")
public String getConfigDescription(String name) {

    JSONArray parameters = new JSONArray();

    try {
        Class<?> clazz = this.plugins.get(name);
        if (clazz != null) {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(ConfigParameter.class)) {

                    JSONObject fieldConfig = new JSONObject();

                    ConfigParameter ann = field.getAnnotation(ConfigParameter.class);

                    fieldConfig.put("name", ann.name());
                    fieldConfig.put("description", ann.description());

                    if (field.isAnnotationPresent(ConfigSelect.class)) {

                        fieldConfig.put("type", "select");

                        ConfigSelect select = field.getAnnotation(ConfigSelect.class);
                        Method method = clazz.getMethod(select.method());
                        List<String> values = (List<String>) method.invoke(null);

                        JSONArray valuesArray = new JSONArray();
                        for (String value : values) {
                            valuesArray.add(value);
                        }

                        fieldConfig.put("values", valuesArray);

                    } else {
                        fieldConfig.put("type", "text");
                    }
                    parameters.add(fieldConfig);
                }
            }
        }
    } catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
    }
    return parameters.toJSONString();
}

From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserBookmarksRepositorySession.java

/**
 * Retrieve the child array for a record, repositioning and updating the database as necessary.
 *
 * @param folderID//  w ww  .  j  ava 2s  .  co  m
 *        The database ID of the folder.
 * @param persist
 *        True if generated positions should be written to the database. The modified
 *        time of the parent folder is only bumped if this is true.
 * @return
 *        An array of GUIDs.
 * @throws NullCursorException
 */
@SuppressWarnings("unchecked")
private JSONArray getChildrenArray(long folderID, boolean persist) throws NullCursorException {
    trace("Calling getChildren for androidID " + folderID);
    JSONArray childArray = new JSONArray();
    Cursor children = dataAccessor.getChildren(folderID);
    try {
        if (!children.moveToFirst()) {
            trace("No children: empty cursor.");
            return childArray;
        }
        final int positionIndex = children.getColumnIndex(BrowserContract.Bookmarks.POSITION);
        final int count = children.getCount();
        Logger.debug(LOG_TAG, "Expecting " + count + " children.");

        // Sorted by requested position.
        TreeMap<Long, ArrayList<String>> guids = new TreeMap<Long, ArrayList<String>>();

        while (!children.isAfterLast()) {
            final String childGuid = getGUID(children);
            final long childPosition = getPosition(children, positionIndex);
            trace("  Child GUID: " + childGuid);
            trace("  Child position: " + childPosition);
            Utils.addToIndexBucketMap(guids, Math.abs(childPosition), childGuid);
            children.moveToNext();
        }

        // This will suffice for taking a jumble of records and indices and
        // producing a sorted sequence that preserves some kind of order --
        // from the abs of the position, falling back on cursor order (that
        // is, creation time and ID).
        // Note that this code is not intended to merge values from two sources!
        boolean changed = false;
        int i = 0;
        for (Entry<Long, ArrayList<String>> entry : guids.entrySet()) {
            long pos = entry.getKey().longValue();
            int atPos = entry.getValue().size();

            // If every element has a different index, and the indices are
            // in strict natural order, then changed will be false.
            if (atPos > 1 || pos != i) {
                changed = true;
            }
            for (String guid : entry.getValue()) {
                if (!forbiddenGUID(guid)) {
                    childArray.add(guid);
                }
            }
        }

        if (Logger.logVerbose(LOG_TAG)) {
            // Don't JSON-encode unless we're logging.
            Logger.trace(LOG_TAG, "Output child array: " + childArray.toJSONString());
        }

        if (!changed) {
            Logger.debug(LOG_TAG, "Nothing moved! Database reflects child array.");
            return childArray;
        }

        if (!persist) {
            return childArray;
        }

        Logger.debug(LOG_TAG, "Generating child array required moving records. Updating DB.");
        final long time = now();
        if (0 < dataAccessor.updatePositions(childArray)) {
            Logger.debug(LOG_TAG, "Bumping parent time to " + time + ".");
            dataAccessor.bumpModified(folderID, time);
        }
    } finally {
        children.close();
    }

    return childArray;
}

From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserBookmarksRepositorySession.java

@Override
protected void updateBookkeeping(Record record)
        throws NoGuidForIdException, NullCursorException, ParentNotFoundException {
    super.updateBookkeeping(record);
    BookmarkRecord bmk = (BookmarkRecord) record;

    // If record is folder, update maps and re-parent children if necessary.
    if (!bmk.isFolder()) {
        Logger.debug(LOG_TAG, "Not a folder. No bookkeeping.");
        return;//from w  w  w .  ja  v  a 2 s . com
    }

    Logger.debug(LOG_TAG, "Updating bookkeeping for folder " + record.guid);

    // Mappings between ID and GUID.
    // TODO: update our persisted children arrays!
    // TODO: if our Android ID just changed, replace parents for all of our children.
    guidToID.put(bmk.guid, bmk.androidID);
    idToGuid.put(bmk.androidID, bmk.guid);

    JSONArray childArray = bmk.children;

    if (Logger.logVerbose(LOG_TAG)) {
        Logger.trace(LOG_TAG, bmk.guid + " has children " + childArray.toJSONString());
    }
    parentToChildArray.put(bmk.guid, childArray);

    // Re-parent.
    if (missingParentToChildren.containsKey(bmk.guid)) {
        for (String child : missingParentToChildren.get(bmk.guid)) {
            // This might return -1; that's OK, the bookmark will
            // be properly repositioned later.
            long position = childArray.indexOf(child);
            dataAccessor.updateParentAndPosition(child, bmk.androidID, position);
            needsReparenting--;
        }
        missingParentToChildren.remove(bmk.guid);
    }
}

From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserHistoryDataExtender.java

/**
 * Store visit data./*from w  ww  .  j  av a 2s.c o m*/
 *
 * If a row with GUID `guid` does not exist, insert a new row.
 * If a row with GUID `guid` does exist, replace the visits column.
 *
 * @param guid The GUID to store to.
 * @param visits New visits data.
 */
public void store(String guid, JSONArray visits) {
    SQLiteDatabase db = this.getCachedWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(COL_GUID, guid);
    if (visits == null) {
        cv.put(COL_VISITS, "[]");
    } else {
        cv.put(COL_VISITS, visits.toJSONString());
    }

    String where = COL_GUID + " = ?";
    String[] args = new String[] { guid };
    int rowsUpdated = db.update(TBL_HISTORY_EXT, cv, where, args);
    if (rowsUpdated >= 1) {
        Logger.debug(LOG_TAG, "Replaced history extension record for row with GUID " + guid);
    } else {
        long rowId = db.insert(TBL_HISTORY_EXT, null, cv);
        Logger.debug(LOG_TAG, "Inserted history extension record into row: " + rowId);
    }
}

From source file:org.mozilla.gecko.sync.repositories.domain.BookmarkRecord.java

private boolean jsonArrayStringsEqual(JSONArray a, JSONArray b) {
    // Check for nulls
    if (a == b)/*from   ww  w  . j a v  a  2 s.c o  m*/
        return true;
    if (a == null && b != null)
        return false;
    if (a != null && b == null)
        return false;
    return RepoUtils.stringsEqual(a.toJSONString(), b.toJSONString());
}

From source file:org.nbgames.core.PlayerManager.java

private void store() {
    JSONArray array = new JSONArray();

    for (Player player : mPlayers) {
        JSONObject object = new JSONObject();
        object.put(KEY_PLAYER_ID, player.getId());
        object.put(KEY_PLAYER_NAME, player.getName());
        object.put(KEY_PLAYER_HANDEDNESS, player.getHandedness().name());
        array.add(object);/* w  w  w. j  a v  a2s.c om*/
    }

    mPreferences.put(KEY_PLAYERS, array.toJSONString());
}