Java Code Examples for org.json.JSONObject#accumulate()

The following examples show how to use org.json.JSONObject#accumulate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonParser.java    From AndroidSDK with Apache License 2.0 6 votes vote down vote up
public JSONObject getCardsCreate(String number, String expire,
    Double amount, Boolean save) {
  JSONObject root = new JSONObject();
  JSONObject params = new JSONObject();
  JSONObject card = new JSONObject();
  try {
    card.accumulate("number", number);
    card.accumulate("expire", expire);
    params.accumulate("card", card);
    params.accumulate("amount", amount);
    params.accumulate("save", save);
    root.accumulate("params", params);
  } catch (Exception e) {
      Logger.d(TAG, e.toString());
  }

  return root;
}
 
Example 2
Source File: Thread.java    From United4 with GNU General Public License v3.0 6 votes vote down vote up
public JSONObject save() throws JSONException {
    JSONObject object = new JSONObject();
    object.accumulate("post_id", post_id);
    object.accumulate("board", board);
    object.accumulate("is_op", is_op);
    object.accumulate("comment", comment);
    object.accumulate("date_posted", date_posted);
    object.accumulate("ip", ip);
    object.accumulate("capcode", capcode);
    object.accumulate("title", title);
    object.accumulate("last_bumped", last_bumped);
    object.accumulate("is_locked", is_locked);
    object.accumulate("number_of_replies", number_of_replies);
    object.accumulate("sticky", sticky);
    object.accumulate("parent", parent);
    object.accumulate("stickyness", stickyness);
    object.accumulate("hash", hash);
    return object;
}
 
Example 3
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Exercise the JSONObject.accumulate() method
 */
@SuppressWarnings("boxing")
@Test
public void jsonObjectAccumulate() {

    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("myArray", true);
    jsonObject.accumulate("myArray", false);
    jsonObject.accumulate("myArray", "hello world!");
    jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!");
    jsonObject.accumulate("myArray", 42);
    jsonObject.accumulate("myArray", -23.45e7);
    // include an unsupported object for coverage
    try {
        jsonObject.accumulate("myArray", Double.NaN);
        fail("Expected exception");
    } catch (JSONException ignored) {}

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
    assertTrue("expected 6 myArray items", ((List<?>)(JsonPath.read(doc, "$.myArray"))).size() == 6);
    assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0")));
    assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1")));
    assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2")));
    assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
    assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
    assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
}
 
Example 4
Source File: FptiManager.java    From braintree_android with MIT License 5 votes vote down vote up
private JSONObject getEventParams(Map<String, String> params) throws JSONException {
    JSONObject ret = new JSONObject();
    for (String key : params.keySet()) {
        ret.accumulate(key, params.get(key));
    }
    return ret;
}
 
Example 5
Source File: DataNode.java    From ambry with Apache License 2.0 5 votes vote down vote up
JSONObject toJSONObject() throws JSONException {
  JSONObject jsonObject = new JSONObject().put("hostname", hostname).put("port", portNum);
  addSSLPortToJson(jsonObject);
  jsonObject.putOpt("rackId", rackId);
  jsonObject.putOpt("xid", xid);
  jsonObject.put("hardwareState",
      dataNodeStatePolicy.isHardDown() ? HardwareState.UNAVAILABLE.name() : HardwareState.AVAILABLE.name())
      .put("disks", new JSONArray());
  for (Disk disk : disks) {
    jsonObject.accumulate("disks", disk.toJSONObject());
  }
  return jsonObject;
}
 
Example 6
Source File: JSONObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAccumulateNull() {
    JSONObject object = new JSONObject();
    try {
        object.accumulate(null, 5);
        fail();
    } catch (JSONException e) {
    }
}
 
Example 7
Source File: HardwareLayout.java    From ambry with Apache License 2.0 5 votes vote down vote up
public JSONObject toJSONObject() throws JSONException {
  JSONObject jsonObject =
      new JSONObject().put("clusterName", clusterName).put("version", version).put("datacenters", new JSONArray());
  for (Datacenter datacenter : datacenters) {
    jsonObject.accumulate("datacenters", datacenter.toJSONObject());
  }
  return jsonObject;
}
 
Example 8
Source File: JSONObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAccumulateExistingArray() throws JSONException {
    JSONArray array = new JSONArray();
    JSONObject object = new JSONObject();
    object.put("foo", array);
    object.accumulate("foo", 5);
    assertEquals("[5]", array.toString());
}
 
Example 9
Source File: JSONObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAccumulateMutatesInPlace() throws JSONException {
    JSONObject object = new JSONObject();
    object.put("foo", 5);
    object.accumulate("foo", 6);
    JSONArray array = object.getJSONArray("foo");
    assertEquals("[5,6]", array.toString());
    object.accumulate("foo", 7);
    assertEquals("[5,6,7]", array.toString());
}
 
Example 10
Source File: EnumTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that enums are handled consistently between JSONArray and JSONObject
 */
@Test
public void verifyEnumConsistency(){
    JSONObject jo = new JSONObject();
    
    jo.put("value", MyEnumField.VAL2);
    String expected="{\"value\":\"VAL2\"}";
    String actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

    jo.accumulate("value", MyEnumField.VAL1);
    expected="{\"value\":[\"VAL2\",\"VAL1\"]}";
    actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

    jo.remove("value");
    jo.append("value", MyEnumField.VAL1);
    expected="{\"value\":[\"VAL1\"]}";
    actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

    jo.put("value", EnumSet.of(MyEnumField.VAL2));
    expected="{\"value\":[\"VAL2\"]}";
    actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

    JSONArray ja = new JSONArray();
    ja.put(MyEnumField.VAL2);
    jo.put("value", ja);
    actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

    jo.put("value", new MyEnumField[]{MyEnumField.VAL2});
    actual = jo.toString();
    assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual));

}
 
Example 11
Source File: NotesClientV02.java    From nextcloud-notes with GNU General Public License v3.0 5 votes vote down vote up
private NoteResponse putNote(SingleSignOnAccount ssoAccount, CloudNote note, String path, String method) throws Exception {
    JSONObject paramObject = new JSONObject();
    paramObject.accumulate(JSON_CONTENT, note.getContent());
    paramObject.accumulate(JSON_MODIFIED, note.getModified().getTimeInMillis() / 1000);
    paramObject.accumulate(JSON_FAVORITE, note.isFavorite());
    paramObject.accumulate(JSON_CATEGORY, note.getCategory());
    return new NoteResponse(requestServer(ssoAccount, path, method, null, paramObject, null));
}
 
Example 12
Source File: NotesClientV1.java    From nextcloud-notes with GNU General Public License v3.0 5 votes vote down vote up
private NoteResponse putNote(SingleSignOnAccount ssoAccount, CloudNote note, String path, String method) throws Exception {
    JSONObject paramObject = new JSONObject();
    paramObject.accumulate(JSON_TITLE, note.getTitle());
    paramObject.accumulate(JSON_CONTENT, note.getContent());
    paramObject.accumulate(JSON_MODIFIED, note.getModified().getTimeInMillis() / 1000);
    paramObject.accumulate(JSON_FAVORITE, note.isFavorite());
    paramObject.accumulate(JSON_CATEGORY, note.getCategory());
    return new NoteResponse(requestServer(ssoAccount, path, method, null, paramObject, null));
}
 
Example 13
Source File: BuildJson1.java    From javase with MIT License 5 votes vote down vote up
public static void main(String[] args) {
try {
       JSONObject dataset = new JSONObject();
       dataset.put("genre_id", 1); 
       dataset.put("genre_parent_id", JSONObject.NULL);
       dataset.put("genre_title", "International");
       // use the accumulate function to add to an existing value. The value
       // will now be converted to a list
       dataset.accumulate("genre_title", "Pop");
       // append to the key
       dataset.append("genre_title", "slow");
       dataset.put("genre_handle", "International");
       dataset.put("genre_color", "#CC3300");
       // get the json array for a string
       System.out.println(dataset.getJSONArray("genre_title"));
       // prints ["International","Pop","slow"]
       // increment a number by 1
       dataset.increment("genre_id");
       // quote a string allowing the json to be delivered within html
       System.out.println(JSONObject.quote(dataset.toString()));
System.out.println("\n\nWrite to the file:\n\n");
System.out.println(dataset.toString());

FileWriter fw = new FileWriter(new File("myJsonObj.json"));
       fw.write(dataset.toString());
       fw.close();

       // prints
       // "{\"genre_color\":\"#CC3300\",\"genre_title\":[\"International\",\"Pop\",\"slow\"],
       // \"genre_handle\":\"International\",\"genre_parent_id\":null,\"genre_id\":2}"
} catch (JSONException jsone) {
	jsone.printStackTrace();
} catch (IOException ioe) {
	ioe.printStackTrace();
}
   }
 
Example 14
Source File: PartitionLayout.java    From ambry with Apache License 2.0 5 votes vote down vote up
public JSONObject toJSONObject() throws JSONException {
  JSONObject jsonObject = new JSONObject().put("clusterName", hardwareLayout.getClusterName())
      .put("version", version)
      .put("partitions", new JSONArray());
  for (Partition partition : partitionMap.values()) {
    jsonObject.accumulate("partitions", partition.toJSONObject());
  }
  return jsonObject;
}
 
Example 15
Source File: JsonParser.java    From AndroidSDK with Apache License 2.0 5 votes vote down vote up
public JSONObject getCardsVerifyCode(String token) {
  JSONObject root = new JSONObject();
  JSONObject params = new JSONObject();

  try {
    params.accumulate("token", token);
    root.accumulate("params", params);
  } catch (Exception e) {
      Logger.d(TAG, e.toString());
  }

  return root;
}
 
Example 16
Source File: JsonRpcRequest.java    From AndroidSDK with Apache License 2.0 5 votes vote down vote up
public String callApiMethod(JSONObject jsonObject, String method) {
  try {
    Logger.d(TAG, method);
    jsonObject.accumulate("method", method);
  } catch (JSONException e) {
      Logger.d(TAG, e.toString());
  }
  return callApi(jsonObject);
}
 
Example 17
Source File: EntityMessage.java    From java-firebase-fcm-client with MIT License 4 votes vote down vote up
/**
 * Generates JSONObject
 * 
 * @return
 */
public JSONObject toJsonObject() {

	final JSONObject json = new JSONObject();

	/**
	 * Reference from firebase * <@see
	 * "https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=en"
	 * >
	 * <p>
	 * This parameter specifies a list of entity(mobile devices,browser
	 * front-end apps)s (registration tokens, or IDs) receiving a multicast
	 * message. It must contain at least 1 and at most 1000 registration
	 * tokens.
	 * 
	 * <p>
	 * Use this parameter only for multicast messaging, not for single
	 * recipients. Multicast messages (sending to more than 1 registration
	 * tokens) are allowed using HTTP JSON format only.
	 * 
	 * <@see
	 * "https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=en"
	 * >
	 */
	final String[] registrationIds = mRegistrationTokenList.toArray(new String[] {});

	// for multicast
	json.accumulate("registration_ids", registrationIds);

	// payload
	/**
	 * Reference from firebase * <@see
	 * "https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=en"
	 * >
	 * <p>
	 * his parameter specifies the custom key-value pairs of the message's
	 * payload.
	 * <p>
	 * For example, with data:{"score":"3x1"}:
	 * <p>
	 * On iOS, if the message is sent via APNS, it represents the custom
	 * data fields. If it is sent via FCM connection server, it would be
	 * represented as key value dictionary in AppDelegate
	 * application:didReceiveRemoteNotification:.
	 * <p>
	 * On Android, this would result in an intent extra named score with the
	 * string value 3x1.
	 * <p>
	 * The key should not be a reserved word ("from" or any word starting
	 * with "google" or "gcm"). Do not use any of the words defined in this
	 * table (such as collapse_key).
	 * <p>
	 * Values in string types are recommended. You have to convert values in
	 * objects or other non-string data types (e.g., integers or booleans)
	 * to string
	 * 
	 */
	json.accumulate("data", mDataMap);

	return json;
}
 
Example 18
Source File: WatchableThread.java    From United4 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public JSONObject save() throws JSONException {
    JSONObject object = super.save();
    object.accumulate("new_replies", new_replies);
    return object;
}
 
Example 19
Source File: KlyphQuery.java    From KlyphMessenger with MIT License 4 votes vote down vote up
/**
 * Assoc a string array with an object array
 */
protected void assocData3(JSONArray initData, JSONArray addData,
		String initKey, String addKey, String putKey)
{
	for (int i = 0; i < initData.length(); i++)
	{
		JSONObject initObject = initData.optJSONObject(i);

		if (initObject.optJSONArray(initKey) != null)
		{
			JSONArray initArray = initObject.optJSONArray(initKey);

			for (int j = 0; j < initArray.length(); j++)
			{
				String value = initArray.optString(j);

				for (int k = 0; k < addData.length(); k++)
				{
					JSONObject addObject = addData.optJSONObject(k);

					if (addObject != null)
					{
						String addValue = addObject.optString(addKey);
						
						if (value.equals(addValue))
						{
							try
							{
								if (initObject.optJSONArray(putKey) == null)
									initObject.putOpt(putKey, new JSONArray());
								
								initObject.accumulate(putKey, addObject);
							}
							catch (JSONException e)
							{
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}
 
Example 20
Source File: KlyphQuery.java    From Klyph with MIT License 4 votes vote down vote up
/**
 * Assoc a string array with an object array
 */
protected void assocData3(JSONArray initData, JSONArray addData, String initKey, String addKey, String putKey)
{
	for (int i = 0; i < initData.length(); i++)
	{
		JSONObject initObject = initData.optJSONObject(i);

		if (initObject.optJSONArray(initKey) != null)
		{
			JSONArray initArray = initObject.optJSONArray(initKey);

			for (int j = 0; j < initArray.length(); j++)
			{
				String value = initArray.optString(j);

				for (int k = 0; k < addData.length(); k++)
				{
					JSONObject addObject = addData.optJSONObject(k);

					if (addObject != null)
					{
						String addValue = addObject.optString(addKey);

						if (value.equals(addValue))
						{
							try
							{
								if (initObject.optJSONArray(putKey) == null)
									initObject.putOpt(putKey, new JSONArray());

								initObject.accumulate(putKey, addObject);
							}
							catch (JSONException e)
							{
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}