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(int index, Object value) throws JSONException 

Source Link

Document

Put or replace an object value in the JSONArray.

Usage

From source file:org.jabsorb.ng.serializer.impl.RawJSONArraySerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    // reprocess the raw json in order to fixup circular references and
    // duplicates
    final JSONArray jsonIn = (JSONArray) o;
    final JSONArray jsonOut = new JSONArray();

    int i = 0;//w ww. ja  va  2  s .co  m
    try {
        final int j = jsonIn.length();

        for (i = 0; i < j; i++) {
            final Object json = ser.marshall(state, o, jsonIn.get(i), new Integer(i));
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                jsonOut.put(i, json);
            } else {
                // put a slot where the object would go, so it can be fixed
                // up properly in the fix up phase
                jsonOut.put(i, JSONObject.NULL);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("element " + i, e);
    } catch (final JSONException e) {
        throw new MarshallException("element " + i, e);
    }
    return jsonOut;
}

From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    final Set<?> set = (Set<?>) o;

    final JSONObject obj = new JSONObject();
    final JSONArray setdata = new JSONArray();
    if (ser.getMarshallClassHints()) {
        try {/*from ww w  . j a v  a 2 s  .  co  m*/
            obj.put("javaClass", o.getClass().getName());
        } catch (final JSONException e) {
            throw new MarshallException("javaClass not found!", e);
        }
    }
    try {
        obj.put("set", setdata);
        state.push(o, setdata, "set");
    } catch (final JSONException e) {
        throw new MarshallException("Could not set 'set': " + e.getMessage(), e);
    }

    Object value = null;
    int idx = 0;
    final Iterator<?> i = set.iterator();
    try {
        while (i.hasNext()) {
            value = i.next();
            final Object json = ser.marshall(state, setdata, value, idx);

            // omit the object entirely if it's a circular reference or
            // duplicate
            // it will be regenerated in the fixups phase
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                setdata.put(idx, json);
            }

            idx++;
        }
    } catch (final MarshallException e) {
        throw new MarshallException("set value " + value + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new MarshallException("set value " + value + " " + e.getMessage(), e);
    } finally {
        state.pop();
    }
    return obj;
}

From source file:com.example.nestedarchetypeactivityexample.InnerArchetypeViewerActivity.java

private JSONArray getTemplateJsonContent() {
    List<WidgetProvider> wps = this.tp.getWidgetProviders();
    JSONArray tmpJson = new JSONArray();
    for (int i = 0; i < wps.size(); i++)
        try {//from   w  w w. jav  a2  s  .c o  m
            tmpJson.put(i, wps.get(i).toJson());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    return tmpJson;

}

From source file:com.mikecorrigan.trainscorekeeper.Game.java

public boolean write(final Context context) {
    Log.vc(VERBOSE, TAG, "write: context=" + context);

    // Ignore any undo events.
    List<ScoreEvent> temp = scoreEvents = scoreEvents.subList(0, lastScoreEvent);

    // Convert the list of events to a JSON array, then convert to a string.
    String string = null;/*from  w ww  . ja  v  a2  s  .c  om*/
    try {
        JSONArray jsonScoreEvents = new JSONArray();
        for (ScoreEvent scoreEvent : temp) {
            JSONObject jsonScoreEvent = scoreEvent.toJson();
            if (jsonScoreEvent == null) {
                Log.w(TAG, "write: skipping score event");
                continue;
            }

            jsonScoreEvents.put(jsonScoreEvents.length(), jsonScoreEvent);
        }

        JSONObject jsonRoot = new JSONObject();
        jsonRoot.put(JsonSpec.SCORES_KEY, jsonScoreEvents);
        jsonRoot.put(JsonSpec.GAME_SPEC, spec);

        string = jsonRoot.toString();
    } catch (JSONException e) {
        Log.th(TAG, e, "write: failed");
        return false;
    }

    // Write the string into a file.
    if (string != null) {
        String path = context.getFilesDir() + File.separator + SAVED_FILE;
        File file = new File(path);
        FileUtils.writeStringToFile(file, string);
    }

    return true;
}

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

/**
 * Recursively searches for JSONObjects, checking if they should be
 * formatted as arrays, then converted./* ww w  . j a  va 2 s .c  o m*/
 *
 * @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.tweetlanes.android.core.App.java

public void onPostSignIn(TwitterUser user, String oAuthToken, String oAuthSecret,
        SocialNetConstant.Type oSocialNetType) {

    if (user != null) {

        try {//w w w. j a v  a 2 s  .c o m

            final Editor edit = mPreferences.edit();
            String userIdAsString = Long.toString(user.getId());

            AccountDescriptor account = new AccountDescriptor(this, user, oAuthToken, oAuthSecret,
                    oSocialNetType, user.getProfileImageUrl(TwitterManager.ProfileImageSize.BIGGER));
            edit.putString(getAccountDescriptorKey(user.getId()), account.toString());

            String accountIndices = mPreferences.getString(SharedPreferencesConstants.ACCOUNT_INDICES, null);
            JSONArray jsonArray;

            if (accountIndices == null) {
                jsonArray = new JSONArray();
                jsonArray.put(0, user.getId());
                mAccounts.add(account);
            } else {
                jsonArray = new JSONArray(accountIndices);
                boolean exists = false;
                for (int i = 0; i < jsonArray.length(); i++) {
                    String c = jsonArray.getString(i);
                    if (c.compareTo(userIdAsString) == 0) {
                        exists = true;
                        mAccounts.set(i, account);
                        break;
                    }
                }

                if (!exists) {
                    jsonArray.put(userIdAsString);
                    mAccounts.add(account);
                }
            }

            accountIndices = jsonArray.toString();
            edit.putString(SharedPreferencesConstants.ACCOUNT_INDICES, accountIndices);

            edit.commit();

            setCurrentAccount(user.getId());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        updateTwitterAccountCount();
        if (TwitterManager.get().getSocialNetType() == oSocialNetType) {
            TwitterManager.get().setOAuthTokenWithSecret(oAuthToken, oAuthSecret, true);
        } else {
            TwitterManager.initModule(oSocialNetType,
                    oSocialNetType == SocialNetConstant.Type.Twitter ? ConsumerKeyConstants.TWITTER_CONSUMER_KEY
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_KEY,
                    oSocialNetType == SocialNetConstant.Type.Twitter
                            ? ConsumerKeyConstants.TWITTER_CONSUMER_SECRET
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_SECRET,
                    oAuthToken, oAuthSecret, getCurrentAccountKey(), mConnectionStatusCallbacks);
        }
    }
}

From source file:org.upv.satrd.fic2.fe.connectors.citySDK.Fusion.java

public static FusionResult fusion(JSONObject poi1, JSONObject poi2, FusionRule fr, Logger log) {

    FusionResult fusionresult = null;/*w w w . j a va  2s  .  c  o m*/
    String name_source = "";
    if (log == null)
        log = Fusion.log;

    try {

        int namePos1 = CommonUtils.getPropertyPos(poi1, "name", log);
        String source1 = poi1.getJSONArray("label").getJSONObject(namePos1).getString("base");
        int namePos2 = CommonUtils.getPropertyPos(poi2, "name", log);
        String source2 = poi2.getJSONArray("label").getJSONObject(namePos2).getString("base");

        //Fusion label tag
        JSONArray object1 = poi1.getJSONArray("label");
        JSONArray object2 = poi2.getJSONArray("label");

        JSONArray object3 = new JSONArray();
        int i = 0;

        //TODO we are not combining the location.address element of both POIs. Now we just take the first one (the one that conditions position)   

        //////////////////////
        //Add name. We take the one that first appears in the name ArrayList
        //////////////////////
        for (int j = 0; j < fr.getName().size(); j++) {
            if (fr.getName().get(j).equals(source1)) {
                int namePos = CommonUtils.getPropertyPos(poi1, "name", log);
                object3.put(i, poi1.getJSONArray("label").getJSONObject(namePos));
                i++;
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source1);
                name_source = source1;
                break;
            }
            if (fr.getName().get(j).equals(source2)) {
                int namePos = CommonUtils.getPropertyPos(poi2, "name", log);
                object3.put(i, poi2.getJSONArray("label").getJSONObject(namePos));
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source2);
                name_source = source2;
                i++;
                break;
            }
        }

        ////////////////////
        //Add other labels
        ////////////////////
        ArrayList<String> allObjects = new ArrayList<String>();

        for (int j = 0; j < object1.length(); j++) {
            //If is not name
            if (!poi1.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi1.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi1.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }

        }
        for (int j = 0; j < object2.length(); j++) {
            //If is not name
            if (!poi2.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi2.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi2.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //We'll store the final POI in poi1. We preserve the structure and override step by step. Up to now only label
        poi1.put("label", object3);

        ///////////////////////////////////
        //Fusion description tag. It is possible that this tag does not appear in some POIs, so we must be careful 
        //////////////////////////////////
        try {
            object1 = poi1.getJSONArray("description");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }
        try {
            object2 = poi2.getJSONArray("description");
        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }

        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
            } else {

                for (int j = 0; j < fr.getDescription().size(); j++) {
                    if (fr.getDescription().get(j).equals(source1)) {
                        if (poi1.getJSONArray("description").length() > 0) {
                            object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
                            log.info("Fusion.fusion(). Fusioning. Inserting description from source: "
                                    + source1);
                            break;
                        }
                    }
                    if (fr.getDescription().get(j).equals(source2)) {
                        if (poi2.getJSONArray("description").length() > 0) {
                            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
                            log.info(
                                    "Fusion.fusion().Fusioning. Inserting description from source: " + source2);
                            break;
                        }
                    }
                }
            }
        }

        //Override description field
        poi1.put("description", object3);

        //////////////////////////
        //Fusion category tag
        /////////////////////////
        try {
            object1 = poi1.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have category.");
        }
        try {
            object2 = poi2.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have category.");
        }

        allObjects = new ArrayList<String>(); //We don't need it as we will add all categories, we'll not check if they are repeated   
        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("category").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("category").getJSONObject(i));
            } else {

                for (int j = 0; j < object1.length(); j++) {
                    String value = (String) object1.getJSONObject(j).get("value");

                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
                for (int j = 0; j < object2.length(); j++) {
                    String value = (String) object2.getJSONObject(j).get("value");

                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }

            }
        }

        //Override category
        poi1.put("category", object3);

        ///////////////////////////
        //Fusion link tag
        ///////////////////////////
        try {
            object1 = poi1.getJSONArray("link");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source1 + " does not have link.");
        }
        try {
            object2 = poi2.getJSONArray("link");

        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source2 + " does not have link.");
        }

        allObjects = new ArrayList<String>();

        object3 = new JSONArray();
        i = 0;

        if (object1 != null) {
            for (int j = 0; j < object1.length(); j++) {
                String value = (String) object1.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        if (object2 != null) {
            for (int j = 0; j < object2.length(); j++) {
                String value = (String) object2.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //Override link
        poi1.put("link", object3);

        //Finally we should override the publisher part to say 'Fusion Engine'. Anyway we can set it up during the storage of the POI in the database

        //Create the FusionResult return object
        fusionresult = new FusionResult(poi1, name_source);

    } catch (Exception e) {
        System.out.println("Error.Fusion.fusion(): " + e.getMessage());
        log.error("Error.Fusion.fusion(): " + e.getMessage());
    }

    return fusionresult;

}

From source file:com.intel.xdk.multitouch.MultiTouch.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True when the action was valid, false otherwise.
 *//*from  www . j av  a  2s.c om*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("enableMultitouch")) {
        enableMultitouch();
    } else if (action.equals("disableMultitouch")) {
        disableMultitouch();
    } else if (action.equals("queueMultitouchData")) {
        queueMultitouchData(args.getString(0), args.getInt(1), args.getInt(2));
    } else if (action.equals("getMultitouchData")) {
        String js = getMultitouchData();
        JSONArray r = new JSONArray(js);
        callbackContext.success(r);
    } else if (action.equals("messagePump")) {
        JSONObject r = new JSONObject();
        r.put("message", new JSONObject(messagePump()));
        callbackContext.success(r);

    } else if (action.equals("addMessage")) {
        addMessage(args.getString(0));
    } else if (action.equals("")) {
        this.enableMultitouch();
    } else {
        return false;
    }

    return true;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * Convert to json job data.//from   ww  w.  j  ava  2s.c  o m
 * @param jobDataList the job data list
 * @param timezone the timezone
 * @return the jSON array
 */
protected JSONArray convertToJSONJobData(List<MockJobData> jobDataList, String timezone) {

    JSONArray jobData = new JSONArray();
    int i = 0;
    for (MockJobData mockJobData : jobDataList) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("start", DateUtil.format(mockJobData.getStart(), "HH:mm:ss"));
            jsonObject.put("end", DateUtil.format(mockJobData.getEnd(), "HH:mm:ss"));
            jsonObject.put("moBlackOut", mockJobData.getBlackout());
            Calendar cuttOffTime = (Calendar) Calendar.getInstance(TimeZone.getTimeZone(timezone)).clone();
            cuttOffTime.set(Calendar.HOUR_OF_DAY, 0);
            cuttOffTime.set(Calendar.MINUTE, 0);
            cuttOffTime.set(Calendar.SECOND, 0);
            if (mockJobData.getCutoff() == null) {
                jsonObject.put("moCutoff", DateUtil.format(cuttOffTime, "HH:mm:ss"));
            } else {
                jsonObject.put("moCutoff", mockJobData.getCutoff());
            }

            jsonObject.put("moRecovery", mockJobData.getRecovery());
            jsonObject.put("deltaEE", mockJobData.getDelta());
            jobData.put(i, jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        i++;
    }
    return jobData;
}

From source file:org.bd2kccc.bd2kcccpubmed.Crawler.java

public static void main(String[] args) {
    HashMap<Integer, ArrayList<String>> publications = new HashMap();

    for (int i = 0; i < BD2K_CENTERS.length; i++) {
        String searchUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term="
                + BD2K_GRANTS[i] + "[Grant%20Number]&retmode=json&retmax=1000";

        System.out.println(searchUrl);
        HttpRequest request = HttpRequest.get(searchUrl);
        JSONObject req = new JSONObject(request.body());
        JSONArray idlist = req.getJSONObject("esearchresult").getJSONArray("idlist");
        System.out.println(BD2K_CENTERS[i] + ": " + idlist.length());
        for (int j = 0; j < idlist.length(); j++) {
            int pmid = idlist.optInt(j);
            if (!publications.containsKey(pmid)) {
                ArrayList<String> centerList = new ArrayList();
                centerList.add(BD2K_CENTERS[i]);
                publications.put(pmid, centerList);
            } else {
                publications.get(pmid).add(BD2K_CENTERS[i]);
            }/*from  w  w w.  j a  va 2  s .c  om*/
        }
    }

    Integer[] pmids = publications.keySet().toArray(new Integer[0]);
    int collaborations = 0;
    for (int i = 0; i < pmids.length; i++)
        if (publications.get(pmids[i]).size() > 1)
            collaborations++;

    System.out.println(pmids.length + " publications found.");
    System.out.println(collaborations + " BD2K Center collaborations found.");
    String summaryUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id="
            + pmids[0];
    for (int i = 1; i < pmids.length; i++)
        summaryUrl += "," + pmids[i];

    System.out.println(summaryUrl);
    HttpRequest request = HttpRequest.get(summaryUrl);
    JSONObject result = new JSONObject(request.body()).getJSONObject("result");

    ArrayList<Publication> publicationStructs = new ArrayList();

    for (int i = 0; i < pmids.length; i++) {
        JSONObject pub = result.getJSONObject("" + pmids[i]);
        Publication publication = new Publication();
        publication.pmid = pmids[i];
        publication.centers = publications.get(pmids[i]);
        publication.name = pub.optString("title", "NO_TITLE");
        //remove &lt;i&gt; and &lt;/i&gt;
        //replace &amp;amp; with &
        publication.name = unescapeHtml4(publication.name);
        publication.date = pub.optString("sortpubdate", "1066/01/01 00:00").substring(0, 10);
        publication.date = publication.date.replaceAll("/", "-");

        JSONArray articleIDs = pub.getJSONArray("articleids");
        for (int j = 0; j < articleIDs.length(); j++) {
            JSONObject id = articleIDs.optJSONObject(j);
            if (id.optString("idtype").equals("doi"))
                publication.doi = id.optString("value");
        }

        String issue = pub.optString("issue");
        if (!issue.isEmpty())
            issue = "(" + issue + ")";

        publication.citation = pub.optString("source") + ". " + pub.optString("pubdate") + ";"
                + pub.optString("volume") + issue + ":" + pub.optString("pages") + ".";

        publication.authors = new ArrayList();
        JSONArray aut = pub.getJSONArray("authors");
        for (int j = 0; j < aut.length(); j++) {
            publication.authors.add(aut.getJSONObject(j).optString("name"));
        }

        publicationStructs.add(publication);
    }

    Collections.sort(publicationStructs);

    for (Publication p : publicationStructs) {
        if (p.isTool())
            System.out.println(p.name);
    }

    JSONArray outputData = new JSONArray();

    for (Publication p : publicationStructs) {
        JSONArray row = new JSONArray();
        row.put(0, p.getName());
        row.put(1, p.getType());
        row.put(2, p.getDate());
        row.put(3, p.getCenter());
        row.put(4, p.getInitiative());
        row.put(5, p.getDescription());
        outputData.put(row);
    }

    System.out.println(outputData.toString(1));

}