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:re.notifica.cordova.NotificarePlugin.java

/**
 * Fetch inbox items//from   w  w w .ja v  a2 s  . com
 * @param args
 * @param callbackContext
 */
protected void fetchInbox(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "FETCHINBOX");
    if (Notificare.shared().getInboxManager() != null) {
        int size = Notificare.shared().getInboxManager().getItems().size();
        int limit = args.optInt(1, DEFAULT_LIST_SIZE);
        if (limit <= 0) {
            limit = DEFAULT_LIST_SIZE;
        }
        int skip = args.optInt(0);
        if (skip < 0) {
            skip = 0;
        }
        if (skip > size) {
            skip = size;
        }
        int end = limit + skip;
        if (end > size) {
            end = size;
        }
        List<NotificareInboxItem> items = new ArrayList<NotificareInboxItem>(
                Notificare.shared().getInboxManager().getItems()).subList(skip, end);
        JSONArray inbox = new JSONArray();
        for (NotificareInboxItem item : items) {
            try {
                JSONObject result = new JSONObject();
                result.put("itemId", item.getItemId());
                result.put("notification", item.getNotification().getNotificationId());
                result.put("message", item.getNotification().getMessage());
                result.put("status", item.getStatus());
                result.put("timestamp", dateFormatter.format(item.getTimestamp()));
                inbox.put(result);
            } catch (JSONException e) {
                // Ignore this item
                Log.w(TAG, "failed to serialize inboxitem: " + e.getMessage());
            }
        }
        if (callbackContext == null) {
            return;
        }
        JSONObject results = new JSONObject();
        try {
            results.put("inbox", inbox);
            results.put("total", size);
            results.put("unread", Notificare.shared().getInboxManager().getUnreadCount());
        } catch (JSONException e) {
            Log.w(TAG, "failed to serialize inbox: " + e.getMessage());
        }
        callbackContext.success(results);
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

From source file:game.objects.Board.java

public JSONArray getBoardJSON() throws JSONException {
    JSONArray arr = new JSONArray();
    for (String key : countries.keySet()) {
        JSONObject json = new JSONObject();
        json.put("CountryID", key);
        json.put("CountryName", countries.get(key).getName());
        json.put("Owner", countries.get(key).getOwner());
        json.put("Troops", countries.get(key).getTroops());
        arr.put(json);
    }/*from  w  ww  .j  a v a2s .  com*/
    return arr;
}

From source file:ai.susi.mind.SusiArgument.java

public JSONObject toJSON() {
    JSONObject json = new JSONObject(true);
    JSONArray recallJson = new JSONArray();
    this.recall.forEach(thought -> recallJson.put(thought));
    JSONArray actionsJson = new JSONArray();
    this.actions.forEach(action -> actionsJson.put(action.toJSONClone()));
    json.put("recall", recallJson);
    json.put("action", actionsJson);
    return json;/*from  w w w .  java  2  s.  co m*/
}

From source file:com.ecml.MidiOptions.java

/** Convert this MidiOptions object into a JSON string. */
public String toJson() {
    try {//from  w  w  w  . j ava2 s.c o m
        JSONObject json = new JSONObject();
        JSONArray jsonTracks = new JSONArray();
        for (boolean value : tracks) {
            jsonTracks.put(value);
        }
        JSONArray jsonMute = new JSONArray();
        for (boolean value : mute) {
            jsonMute.put(value);
        }
        JSONArray jsonInstruments = new JSONArray();
        for (int value : instruments) {
            jsonInstruments.put(value);
        }
        if (time != null) {
            JSONObject jsonTime = new JSONObject();
            jsonTime.put("numerator", time.getNumerator());
            jsonTime.put("denominator", time.getDenominator());
            jsonTime.put("quarter", time.getQuarter());
            jsonTime.put("tempo", time.getTempo());
            json.put("time", jsonTime);
        }

        json.put("versionCode", 7);
        json.put("tracks", jsonTracks);
        json.put("mute", jsonMute);
        json.put("instruments", jsonInstruments);
        json.put("useDefaultInstruments", useDefaultInstruments);
        json.put("scrollVert", scrollVert);
        json.put("showPiano", showPiano);
        json.put("showNoteColors", showNoteColors);
        json.put("showLyrics", showLyrics);
        json.put("delay", delay);
        json.put("twoStaffs", twoStaffs);
        json.put("showNoteLetters", showNoteLetters);
        json.put("transpose", transpose);
        json.put("key", key);
        json.put("combineInterval", combineInterval);
        json.put("shade1Color", shade1Color);
        json.put("shade2Color", shade2Color);
        json.put("showMeasures", showMeasures);
        json.put("playMeasuresInLoop", playMeasuresInLoop);
        json.put("playMeasuresInLoopStart", playMeasuresInLoopStart);
        json.put("playMeasuresInLoopEnd", playMeasuresInLoopEnd);

        return json.toString();
    } catch (JSONException e) {
        return null;
    } catch (NullPointerException e) {
        return null;
    }
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Convert an old favourites string to the new JSON format
 * @param favouriteString/*from   www .j a v a2s.  c  om*/
 * @return JSONArray
 */
private String convertOldFavourites(String favouriteString) {

    try {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        int tramTrackerId;

        StringTokenizer tokenizer = new StringTokenizer(favouriteString, ",");
        while (tokenizer.hasMoreTokens()) {
            tramTrackerId = Integer.parseInt(tokenizer.nextToken());
            jsonObject = new JSONObject();
            jsonObject.put("stop", tramTrackerId);
            jsonArray.put(jsonObject);
        }
        return jsonArray.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Generate a JSON string serializing our favourites
 *//*  w  w  w. jav a 2 s . c o  m*/
public JSONArray getFavouritesJSON() {

    JSONArray jsonArray = new JSONArray();

    for (Favourite favourite : mFavourites) {
        jsonArray.put(favourite.getFavouriteJSON());
    }

    return jsonArray;
}

From source file:org.apache.usergrid.chop.webapp.service.chart.series.Series.java

public JSONArray getJsonArray() {

    JSONArray arr = new JSONArray();

    for (Point p : getPoints()) {
        arr.put(p.toJson());
    }/*from   w  ww.ja v  a 2s . c  o  m*/

    return arr;
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;/*from www .  ja va 2s . c  o  m*/
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}

From source file:it.acutus.utilitylibrarycode.parser.XmlToJson.java

private JSONObject convertTagToJson(Tag tag) {
    JSONObject json = new JSONObject();

    // Content is injected as a key/value
    if (tag.getContent() != null) {
        try {//from   w w w . ja v a  2 s. c o m
            String path = tag.getPath();
            String name = getContentNameReplacement(path, DEFAULT_CONTENT_NAME);
            json.put(name, tag.getContent());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    try {
        if (tag.isList() || isForcedList(tag)) {
            JSONArray list = new JSONArray();
            ArrayList<Tag> children = tag.getChildren();
            for (Tag child : children) {
                list.put(convertTagToJson(child));
            }
            String childrenNames = tag.getChild(0).getName();
            json.put(childrenNames, list);
            return json;
        } else {
            ArrayList<Tag> children = tag.getChildren();
            if (children.size() == 0) {
                json.put(tag.getName(), tag.getContent());
            } else {
                for (Tag child : children) {
                    if (child.hasChildren()) {
                        JSONObject jsonChild = convertTagToJson(child);
                        json.put(child.getName(), jsonChild);
                    } else {
                        json.put(child.getName(), child.getContent());
                    }
                }
            }
            return json;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.wso2.emm.agent.services.ProcessMessage.java

private void messageExecute(String msg) {
    stillProcessing = true;// w  w w .  j a va  2  s  .  com
    JSONArray repArray = new JSONArray();
    JSONObject jsReply = null;
    String msgId = "";

    JSONArray dataReply = null;
    try {
        JSONArray jArr = new JSONArray(msg.trim());
        for (int i = 0; i < jArr.length(); i++) {
            JSONArray innerArr = new JSONArray(jArr.getJSONObject(i).getString("data"));
            String featureCode = jArr.getJSONObject(i).getString("code");
            dataReply = new JSONArray();
            jsReply = new JSONObject();
            jsReply.put("code", featureCode);

            for (int x = 0; x < innerArr.length(); x++) {
                msgId = innerArr.getJSONObject(x).getString("messageId");
                jsReply.put("messageId", msgId);

                if (featureCode.equals(CommonUtilities.OPERATION_POLICY_BUNDLE)) {
                    SharedPreferences mainPrefp = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);

                    Editor editorp = mainPrefp.edit();
                    editorp.putString("policy", "");
                    editorp.commit();

                    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
                    Editor editor = mainPref.edit();
                    String arrToPut = innerArr.getJSONObject(0).getJSONArray("data").toString();

                    editor.putString("policy", arrToPut);
                    editor.commit();
                }

                String msgData = innerArr.getJSONObject(x).getString("data");
                JSONObject dataObj = new JSONObject("{}");
                operation = new Operation(context);
                if (featureCode.equalsIgnoreCase(CommonUtilities.OPERATION_POLICY_REVOKE)) {
                    operation.operate(featureCode, jsReply);
                    jsReply.put("status", msgId);
                } else {
                    if (msgData.charAt(0) == '[') {
                        JSONArray dataArr = new JSONArray(msgData);
                        for (int a = 0; a < dataArr.length(); a++) {
                            JSONObject innterDataObj = dataArr.getJSONObject(a);
                            featureCode = innterDataObj.getString("code");
                            String dataTemp = innterDataObj.getString("data");
                            if (!dataTemp.isEmpty() && dataTemp != null && !dataTemp.equalsIgnoreCase("null"))
                                dataObj = innterDataObj.getJSONObject("data");

                            dataReply = operation.operate(featureCode, dataObj);
                            //dataReply.put(resultJson);
                        }
                    } else {
                        if (!msgData.isEmpty() && msgData != null && !msgData.equalsIgnoreCase("null"))
                            if (msgData.charAt(0) == '{') {
                                dataObj = new JSONObject(msgData);
                            }
                        dataReply = operation.operate(featureCode, dataObj);
                        //dataReply.put(resultJson);
                    }
                }

            }
            jsReply.put("data", dataReply);
            repArray.put(jsReply);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (Operation.enterpriseWipe == false) {
            SharedPreferences mainPref = context.getSharedPreferences(
                    context.getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE);
            String regId = mainPref.getString(context.getResources().getString(R.string.shared_pref_regId), "");
            PayloadParser ps = new PayloadParser();

            replyPayload = ps.generateReply(repArray, regId);
            if (CommonUtilities.DEBUG_MODE_ENABLED) {
                Log.e(TAG, "replyPlayload -" + replyPayload);
            }
            stillProcessing = false;
            getOperations(replyPayload);
        }

    }

}