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(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:com.nosoop.json.VDF.java

/**
 * Recursively searches for JSONObjects, checking if they should be
 * formatted as arrays, then converted.//from   ww w  .  ja va2s .  c  om
 *
 * @param object An input JSONObject converted from VDF.
 * @return JSONObject containing the input JSONObject with objects changed
 * to arrays where applicable.
 * @throws JSONException
 */
private static JSONObject convertVDFArrays(JSONObject object) throws JSONException {
    JSONObject resp = new JSONObject();

    if (!object.keys().hasNext()) {
        return resp;
    }

    for (@SuppressWarnings("unchecked")
    Iterator<String> iter = object.keys(); iter.hasNext();) {
        String name = iter.next();
        JSONObject thing = object.optJSONObject(name);

        if (thing != null) {
            // Note:  Empty JSONObjects are also treated as arrays.
            if (containsVDFArray(thing)) {
                @SuppressWarnings("unchecked")
                Iterator<String> iter2 = thing.keys();
                List<String> sortingKeys = new ArrayList<String>();
                while (iter2.hasNext())
                    sortingKeys.add(iter2.next());
                Collections.sort(sortingKeys, new Comparator<String>() {
                    // Integers-as-strings comparator.
                    @Override
                    public int compare(String t, String t1) {
                        int i = Integer.parseInt(t), i1 = Integer.parseInt(t1);
                        return i - i1;
                    }
                });

                JSONArray sortedKeys = new JSONArray(sortingKeys);

                if (sortedKeys.length() > 0) {
                    JSONArray sortedObjects = thing.toJSONArray(sortedKeys);

                    for (int i = 0; i < sortedObjects.length(); i++) {
                        JSONObject arrayObject = sortedObjects.getJSONObject(i);

                        /**
                         * See if any values are also JSONObjects that
                         * should be arrays.
                         */
                        sortedObjects.put(i, convertVDFArrays(arrayObject));
                    }

                    /**
                     * If this JSONObject represents a non-empty array in
                     * VDF format, convert it to a JSONArray.
                     */
                    resp.put(name, sortedObjects);
                } else {
                    /**
                     * If this JSONObject represents an empty array, give it
                     * an empty JSONArray.
                     */
                    resp.put(name, new JSONArray());
                }
            } else {
                /**
                 * If this JSONObject is not a VDF array, see if its values
                 * are before adding.
                 */
                resp.put(name, convertVDFArrays(thing));
            }
        } else {
            /**
             * It's a plain data value. Add it in.
             */
            resp.put(name, object.get(name));
        }
    }

    /**
     * Return the converted JSONObject.
     */
    return resp;
}

From source file:com.adintellig.UDFJson.java

private Object extract_json_withindex(Object json, ArrayList<String> indexList) throws JSONException {

    jsonList.clear();/*from ww  w.  j av  a 2 s . com*/
    jsonList.add(json);
    Iterator<String> itr = indexList.iterator();
    while (itr.hasNext()) {
        String index = itr.next();
        ArrayList<Object> tmp_jsonList = new ArrayList<Object>();
        if (index.equalsIgnoreCase("*")) {
            for (int i = 0; i < (jsonList).size(); i++) {
                try {
                    JSONArray array = (JSONArray) (jsonList).get(i);
                    for (int j = 0; j < array.length(); j++) {
                        tmp_jsonList.add(array.get(j));
                    }
                } catch (Exception e) {
                    continue;
                }
            }
            jsonList = tmp_jsonList;
        } else {
            for (int i = 0; i < (jsonList).size(); i++) {
                try {
                    tmp_jsonList.add(((JSONArray) (jsonList).get(i)).get(Integer.parseInt(index)));
                } catch (ClassCastException e) {
                    continue;
                } catch (JSONException e) {
                    return null;
                }
                jsonList = tmp_jsonList;
            }
        }
    }
    return (jsonList.size() > 1) ? new JSONArray(jsonList) : jsonList.get(0);
}

From source file:org.neomatrix369.examples.twitter.TweetsDataStorageTest.java

@Test
public void shouldBeAbleToWriteAndReadBackMessages() throws JSONException {
    String arrayPartOfTweetAsString = "[{'from_user_name':'someUser', 'from_user_id':'?@someonesTwitterHandle', 'text':'Body of the twitter message #hashtag1 #hashtag2 #hashtag3'}]";
    final String tweetMessageWrittenAsString = "{results: " + arrayPartOfTweetAsString + "}";
    storage.saveTweetMessage(tweetMessageWrittenAsString);

    final JSONArray tweetMessageRead = storage.loadTweetMessage();

    final JSONArray tweetMessageWrittenAsArray = new JSONArray(arrayPartOfTweetAsString);
    assertThat(READ_WRITE_MISMATCH_ERROR_MESSAGE, tweetMessageRead.toString(),
            is(tweetMessageWrittenAsArray.toString()));
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

/**
 * Returns snapshot at index modulo the length of the list, if index is < 0, it returns a random snapshot
 *//*from   www .  j a  v a  2 s.  co m*/
private static List<WifiReading> getSnapshot(int index, Context c) {
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can at least read the external storage
        File root = c.getExternalCacheDir();
        File[] snapshotFiles = root.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String filename) {
                if (filename.endsWith(FILE_EXTENSION)) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (snapshotFiles.length > 0) {
            if (index < 0) {
                Random rand = new Random();
                index = rand.nextInt(snapshotFiles.length);
            } else {
                index = index % snapshotFiles.length;
            }
            try {
                // read file into a string
                FileInputStream fstream = new FileInputStream(snapshotFiles[index]);
                Log.d(TAG, snapshotFiles[index].getName());
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String fileContents = "";
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    fileContents += strLine;
                }

                // make a json array out of the string
                JSONArray json = new JSONArray(fileContents);

                // parse the json array
                return jsonToReadings(json);
            } catch (Exception e) {
                Log.e(TAG, "Could not read file.");
                return null;
            }
        } else {
            // there are no cached snapshots
            return null;
        }
    } else {
        // we cannot read the external storage
        return null;
    }
}

From source file:curso.android.DAO.RespostaDAO.java

public static void atualizaRespostas() {
    try {//from w w  w. j  a  v a 2  s.  co m
        deleteAll();
        String retorno = Const.webService.doPost(Const.METODO_LISTA_RESPOSTA, new ArrayList<NameValuePair>());
        JSONArray jArray = new JSONArray(retorno);
        RespostaDAO.insertLista(jArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:services.LoginRest.java

/**
 *
 * @param username/* ww w. jav a  2 s. c  om*/
 * @return
 */
@GET
@Path("/getUserParams")
@Produces("application/json")
public Response getUserParams(@QueryParam("username") String username) {
    UserController userControl = new UserController();
    JSONArray json = new JSONArray(userControl.getPlayerMeta(username));
    System.out.println("LoginControl user: " + json);
    return Response.ok("{ \"meta\":  " + json + " }").build();
}

From source file:net.homelinux.penecoptero.android.citybikes.app.AccountHelper.java

/**
 * @return Returns a List of cities. Each city is described in a Map of Strings.
 * Each Map contains a "code" value for the city code and a "name" value containing
 * the name of the city./*  w  w  w.jav  a 2s.  c  o  m*/
 */
public List<Map<String, String>> getCities() {
    try {
        String citiesString = getUrl(SERVER_URL + "/contracts/full");
        JSONArray cities = new JSONArray(citiesString);
        ArrayList<Map<String, String>> citiesList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < cities.length(); i++) {
            JSONObject city = cities.getJSONObject(i);
            Map<String, String> cityMap = new HashMap<String, String>(2);
            cityMap.put("code", city.getString("code"));
            cityMap.put("name", city.getString("name"));
            citiesList.add(cityMap);
        }
        return citiesList;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return new ArrayList<Map<String, String>>();
    }
}

From source file:org.apache.giraph.graph.BspServiceWorker.java

/**
 * Get values of aggregators aggregated by master in previous superstep.
 *
 * @param superstep Superstep to get the aggregated values from
 *///w w  w .j  a  v  a  2 s.c om
private void getAggregatorValues(long superstep) {
    String mergedAggregatorPath = getMergedAggregatorPath(getApplicationAttempt(), superstep - 1);
    JSONArray aggregatorArray = null;
    try {
        byte[] zkData = getZkExt().getData(mergedAggregatorPath, false, null);
        aggregatorArray = new JSONArray(new String(zkData));
    } catch (KeeperException.NoNodeException e) {
        LOG.info("getAggregatorValues: no aggregators in " + mergedAggregatorPath + " on superstep "
                + superstep);
        return;
    } catch (KeeperException e) {
        throw new IllegalStateException(
                "Failed to get data for " + mergedAggregatorPath + " with KeeperException", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException(
                "Failed to get data for " + mergedAggregatorPath + " with InterruptedException", e);
    } catch (JSONException e) {
        throw new IllegalStateException(
                "Failed to get data for " + mergedAggregatorPath + " with JSONException", e);
    }
    for (int i = 0; i < aggregatorArray.length(); ++i) {
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("getAggregatorValues: " + "Getting aggregators from "
                        + aggregatorArray.getJSONObject(i));
            }
            String aggregatorName = aggregatorArray.getJSONObject(i).getString(AGGREGATOR_NAME_KEY);
            Aggregator<Writable> aggregator = getAggregatorMap().get(aggregatorName);
            if (aggregator == null) {
                continue;
            }
            Writable aggregatorValue = aggregator.getAggregatedValue();
            InputStream input = new ByteArrayInputStream(
                    Base64.decode(aggregatorArray.getJSONObject(i).getString(AGGREGATOR_VALUE_KEY)));
            aggregatorValue.readFields(new DataInputStream(input));
            aggregator.setAggregatedValue(aggregatorValue);
            if (LOG.isDebugEnabled()) {
                LOG.debug("getAggregatorValues: " + "Got aggregator=" + aggregatorName + " value="
                        + aggregatorValue);
            }
        } catch (JSONException e) {
            throw new IllegalStateException("Failed to decode data for index " + i + " with KeeperException",
                    e);
        } catch (IOException e) {
            throw new IllegalStateException("Failed to decode data for index " + i + " with KeeperException",
                    e);
        }
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("getAggregatorValues: Finished loading " + mergedAggregatorPath + " with aggregator values "
                + aggregatorArray);
    }
}

From source file:eu.the4thfloor.volleyextended.toolbox.JsonArrayRequest.java

@Override
protected Response<JSONArray> parseNetworkResponse(final NetworkResponse response) {

    try {/*from  w  w w  .  j av  a2s .com*/
        final String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
    } catch (final UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (final JSONException je) {
        return Response.error(new ParseError(je));
    }
}

From source file:r2b.apps.utils.FileUtils.java

/**
 * Get a json entity from asset file.//  w  ww  .  j ava2 s .c  o  m
 * @param context The application context.
 * @param assetFile The asset file resource id.
 * @return The JSONArray/JSONObject or null if error.
 */
public synchronized static Object getJsonFromAssetsFile(Context context, int assetFile) {
    BufferedReader reader = null;
    Object json = null;

    try {
        InputStream inputStream = context.getResources().openRawResource(assetFile);
        reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder builder = new StringBuilder();

        String mLine = reader.readLine();
        String firstLine = mLine;
        while (mLine != null) {
            mLine = reader.readLine();
            builder.append(mLine);
        }

        if (firstLine.charAt(0) == '[') {
            json = new JSONArray(builder.toString());
        } else {
            json = new JSONObject(builder.toString());
        }

    } catch (IOException e) {
        Logger.e(FileUtils.class.getSimpleName(), e.toString());
    } catch (JSONException e) {
        Logger.e(FileUtils.class.getSimpleName(), e.toString());
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Logger.e(FileUtils.class.getSimpleName(), e.toString());
            }
        }
    }

    return json;
}