Java Code Examples for org.json.JSONStringer

The following examples show how to use org.json.JSONStringer. These examples are extracted from open source projects. 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 Project: Hook   Source File: PreUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void putMap(String key, Map<Integer, String> age2nameMap) {
    if (age2nameMap != null) {
        JSONStringer jsonStringer = new JSONStringer();
        try {
            jsonStringer.array();
            for (Integer integer : age2nameMap.keySet()) {
                jsonStringer.object();
                jsonStringer.key("age");
                jsonStringer.value(integer);
                jsonStringer.key("name");
                jsonStringer.value(age2nameMap.get(integer));
                jsonStringer.endObject();
            }
            jsonStringer.endArray();
        } catch (JSONException e) {
            e.printStackTrace();
        }
       sp.edit().putString(key, jsonStringer.toString()).commit();
    }
}
 
Example 2
Source Project: accept-sdk-android   Source File: AcceptSDKParser.java    License: MIT License 6 votes vote down vote up
/**
 * Method create Json Object for Encryption API call. Using this method order of insertion is
 * preserved.
 *
 * @param transactionObject encryption transaction Object. Also see {@link
 * EncryptTransactionObject}
 * @return String json String
 * @throws JSONException, exception will be thrown when creation of Json fails.
 */
public static String getOrderedJsonFromEncryptTransaction(
    EncryptTransactionObject transactionObject) throws JSONException {

  // Json related to token section
  CardData cardData = transactionObject.getCardData();

  JSONStringer stringer = new JSONStringer().object();
  stringer.key(CONTAINER_REQUEST).object();
  prepareJsonForAuthenticationSection(stringer, transactionObject);
  stringer.key(CLIENT_ID).value(CLIENT_ID_VALUE);
  stringer.key(DATA).object(); //Data section
  stringer.key(TYPE).value(TYPE_VALUE_TOKEN);
  stringer.key(ID).value(transactionObject.getGuid());
  prepareJsonForTokenSection(stringer, cardData);
  stringer.endObject();
  stringer.endObject();
  stringer.endObject();

  LogUtil.log(LOG_LEVEL.INFO, "getJsonFromEncryptTransaction : " + stringer.toString());
  return stringer.toString();
}
 
Example 3
Source Project: accept-sdk-android   Source File: AcceptSDKParser.java    License: MIT License 6 votes vote down vote up
public static void prepareJsonForAuthenticationSection(JSONStringer stringer,
    EncryptTransactionObject transactionObject) throws JSONException {
  String clientKey = null;
  FingerPrintData fData = null;
  String apiLoginId = transactionObject.getMerchantAuthentication().getApiLoginID();
  MerchantAuthenticationType authenticationType =
      transactionObject.getMerchantAuthentication().getMerchantAuthenticationType();
  if (authenticationType == MerchantAuthenticationType.CLIENT_KEY) {
    ClientKeyBasedMerchantAuthentication clientKeyAuth =
        (ClientKeyBasedMerchantAuthentication) transactionObject.getMerchantAuthentication();
    clientKey = clientKeyAuth.getClientKey();
  } else if (authenticationType == MerchantAuthenticationType.FINGERPRINT) {
    FingerPrintBasedMerchantAuthentication fingerPrintAuth =
        (FingerPrintBasedMerchantAuthentication) transactionObject.getMerchantAuthentication();
    fData = fingerPrintAuth.getFingerPrintData();
  }
  stringer.key(MERCHANT_AUTHENTICATION).object(); //Merchant Authentication section
  stringer.key(Authentication.NAME).value(apiLoginId);
  if (clientKey != null) {
    stringer.key(Authentication.CLIENT_KEY).value(clientKey);
  } else if (fData != null) {
    prepareJsonForFingerPrintSection(stringer, fData);
  }

  stringer.endObject();
}
 
Example 4
Source Project: yawl   Source File: Utils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * serialize String keys and String values in JSON format, sort keys
 * according to order in sortedList
 * 
 * @param map
 * @return
 */
public static String getJSON(List<String> sortedList, Map<String, Object> map) throws Exception
{
	try
	{
		JSONStringer js = new JSONStringer();
		js.object();
		if (map != null)
		{
			for (String key : sortedList)
			{
				js.key(key);
				js.value(map.get(key));
			}
		}
		js.endObject();
		return js.toString();
	}
	catch (JSONException e)
	{
		throw new Exception("cannot produce JSON", e);
	}
}
 
Example 5
Source Project: yawl   Source File: Utils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * serialize String values in JSON format
 * 
 * @param array
 * @return
 */
public static String getJSON(String[] array) throws Exception
{
	try
	{
		JSONStringer js = new JSONStringer();
		js.array();
		if (array != null)
		{
			for (String value : array)
			{
				js.value(value);
			}
		}
		js.endArray();
		return js.toString();
	}
	catch (JSONException e)
	{
		throw new Exception("cannot produce JSON", e);
	}
}
 
Example 6
Source Project: android-test   Source File: ModelCodec.java    License: Apache License 2.0 6 votes vote down vote up
/** Encodes a Java Object into a JSON string. */
public static String encode(Object javaObject) {
  checkNotNull(javaObject);
  try {
    if (javaObject instanceof JSONObject) {
      return javaObject.toString();
    } else if (javaObject instanceof JSONArray) {
      return javaObject.toString();
    } else if (javaObject instanceof JSONAble) {
      return new JSONObject(((JSONAble) javaObject).toJSONString()).toString();
    } else if ((javaObject instanceof Iterable)
        || (javaObject instanceof Map)
        || (javaObject instanceof Object[])) {
      JSONStringer stringer = new JSONStringer();
      return encodeHelper(javaObject, stringer).toString();
    }
    throw new IllegalArgumentException(
        String.format(
            "%s: not a valid top level class. Want one of: %s",
            javaObject.getClass(), TOP_LEVEL_CLASSES));
  } catch (JSONException je) {
    throw new RuntimeException("Encode failed: " + javaObject, je);
  }
}
 
Example 7
Source Project: android-test   Source File: Evaluation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toJSONString() {
  try {
    JSONStringer stringer =
        new JSONStringer().object().key(STATUS_KEY).value(status).key(VALUE_KEY);
    if ((value instanceof String)
        || (value instanceof Number)
        || (value instanceof Boolean)
        || (value == null)) {
      stringer.value(value);
    } else {
      String jsonValue = ModelCodec.encode(value);
      stringer.value(new JSONTokener(jsonValue).nextValue());
    }
    stringer.endObject();
    return stringer.toString();
  } catch (JSONException je) {
    throw new RuntimeException(je);
  }
}
 
Example 8
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testMaxDepthWithObjectValue() throws JSONException {
    JSONObject object = new JSONObject();
    object.put("a", false);
    JSONStringer stringer = new JSONStringer();
    for (int i = 0; i < 20; i++) {
        stringer.object();
        stringer.key("b");
    }
    stringer.value(object);
    for (int i = 0; i < 20; i++) {
        stringer.endObject();
    }
    assertEquals("{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":" +
            "{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":" +
            "{\"a\":false}}}}}}}}}}}}}}}}}}}}}", stringer.toString());
}
 
Example 9
Source Project: orion.server   Source File: JSONUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static String buildJSON(Map<String, Object> params) throws JSONException {
    final JSONStringer stringer = new JSONStringer();
    stringer.object();

    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (param.getKey() != null && !"".equals(param.getKey()) && param.getValue() != null && !""
            .equals(param.getValue())) {
            stringer.key(param.getKey()).value(param.getValue());
        }
    }

    return stringer.endObject().toString();
}
 
Example 10
Source Project: AutoInteraction-Library   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param key
 * @param value
 * @return
 * @throws
 * @Title: createJsonString
 * @Description: 生成json字符串
 * @return: String
 */
public static String createJsonString(String key, JSONArray value) {
    JSONStringer jsonStringer = new JSONStringer();
    try {
        jsonStringer.object().key(key).value(value).endObject();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonStringer.toString();
}
 
Example 11
/**
 * This test method restores some deleted nodes from the archive store.
 */
public void testRestoreDeletedItems() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    JSONObject archivedNodesJson = getArchivedNodes();
    JSONObject dataJsonObj = archivedNodesJson.getJSONObject("data");
    JSONArray archivedNodesArray = dataJsonObj.getJSONArray(AbstractArchivedNodeWebScript.DELETED_NODES);
    
    int archivedNodesLength = archivedNodesArray.length();
    assertTrue("Insufficient archived nodes for test to run.", archivedNodesLength > 1);
    
    // Take a specific archived node and restore it.
    JSONObject firstArchivedNode = archivedNodesArray.getJSONObject(0);
    
    // So we have identified a specific Node in the archive that we want to restore.
    String nodeRefString = firstArchivedNode.getString(AbstractArchivedNodeWebScript.NODEREF);
    assertTrue("nodeRef string is invalid", NodeRef.isNodeRef(nodeRefString));
    NodeRef nodeRef = new NodeRef(nodeRefString);
    
    // This is not the StoreRef where the node originally lived e.g. workspace://SpacesStore
    // This is its current StoreRef i.e. archive://SpacesStore
    final StoreRef currentStoreRef = nodeRef.getStoreRef();
    
    String restoreUrl = getArchiveUrl(currentStoreRef) + "/" + nodeRef.getId();
    
    
    int archivedNodesCountBeforeRestore = getArchivedNodesCount();

    // Send the PUT REST call.
    String jsonString = new JSONStringer().object()
        .key("restoreLocation").value("")
        .endObject()
    .toString();
    Response rsp = sendRequest(new PutRequest(restoreUrl, jsonString, "application/json"), 200);
    
    assertEquals("Expected archive to shrink by one", archivedNodesCountBeforeRestore - 1, getArchivedNodesCount());
}
 
Example 12
/**
 * This test method restores some deleted nodes from the archive store for the current user.
 */
public void testRestoreDeletedItemsAsNonAdminUser() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);

    String restoreUrl = getArchiveUrl(user2_DeletedTestNode.getStoreRef()) + "/" + user2_DeletedTestNode.getId();

    String jsonString = new JSONStringer().object().key("restoreLocation").value("").endObject().toString();
    
    // User_One has the nodeRef of the node deleted by User_Two. User_One is
    // not an Admin, so he must not be allowed to restore a node which he doesn’t own.
    Response rsp = sendRequest(new PutRequest(restoreUrl, jsonString, "application/json"), 403);
    assertEquals(403, rsp.getStatus());
    
    // Now User_One gets his own archived node and tries to restore it
    JSONObject jsonRsp = getArchivedNodes();
    JSONObject dataObj = (JSONObject) jsonRsp.get(DATA);
    JSONArray deletedNodesArray = (JSONArray) dataObj.get(AbstractArchivedNodeWebScript.DELETED_NODES);

    // User_One deleted only 1 node and he doesn't have permission to see other users' archived data.
    assertEquals("Unexpectedly found more than 1 item in the archive store.", 1, deletedNodesArray.length());
    JSONObject archivedNode = (JSONObject) deletedNodesArray.get(0);

    // So we have identified a specific Node in the archive that we want to restore.
    String nodeRefString = archivedNode.getString(AbstractArchivedNodeWebScript.NODEREF);
    assertTrue("nodeRef string is invalid", NodeRef.isNodeRef(nodeRefString));

    NodeRef nodeRef = new NodeRef(nodeRefString);

    // This is its current StoreRef i.e. archive://SpacesStore
    restoreUrl = getArchiveUrl(nodeRef.getStoreRef()) + "/" + nodeRef.getId();
    
    int archivedNodesCountBeforeRestore = getArchivedNodesCount();

    // Send the PUT REST call.
    jsonString = new JSONStringer().object().key("restoreLocation").value("").endObject().toString();
    rsp = sendRequest(new PutRequest(restoreUrl, jsonString, "application/json"), 200);
    
    assertEquals("Expected archive to shrink by one", archivedNodesCountBeforeRestore - 1, getArchivedNodesCount());        
}
 
Example 13
Source Project: accept-sdk-android   Source File: AcceptSDKParser.java    License: MIT License 5 votes vote down vote up
public static void prepareJsonForTokenSection(JSONStringer stringer, CardData cardData)
    throws JSONException {
  stringer.key(TOKEN).object();
  stringer.key(Card.CARD_NUMBER).value(cardData.getCardNumber());
  stringer.key(Card.EXPIRATION_DATE).value(cardData.getExpirationInFormatMMYYYY());
  if (cardData.getCvvCode() != null) stringer.key(Card.CARD_CODE).value(cardData.getCvvCode());
  if (cardData.getZipCode() != null) stringer.key(Card.ZIP).value(cardData.getZipCode());
  if (cardData.getCardHolderName() != null) {
    stringer.key(Card.CARD_HOLDER_NAME).value(cardData.getCardHolderName());
  }
  stringer.endObject();
}
 
Example 14
Source Project: accept-sdk-android   Source File: AcceptSDKParser.java    License: MIT License 5 votes vote down vote up
public static void prepareJsonForFingerPrintSection(JSONStringer stringer, FingerPrintData fData)
    throws JSONException {
  stringer.key(Authentication.FINGER_PRINT).object(); //Fingerprint section
  stringer.key(FingerPrint.HASH_VALUE).value(fData.getHashValue());
  if (fData.getSequence() != null) stringer.key(FingerPrint.SEQUENCE).value(fData.getSequence());
  stringer.key(FingerPrint.TIME_STAMP).value(fData.getTimestampString());
  if (fData.getCurrencyCode() != null) {
    stringer.key(FingerPrint.CURRENCY_CODE).value(fData.getCurrencyCode());
  }
  if (fData.getAmountString() != null) {
    stringer.key(FingerPrint.AMOUNT).value(fData.getAmountString());
  }
  stringer.endObject();
}
 
Example 15
Source Project: TurboLauncher   Source File: InstallShortcutReceiver.java    License: Apache License 2.0 5 votes vote down vote up
private static void addToInstallQueue(
        SharedPreferences sharedPrefs, PendingInstallShortcutInfo info) {
    synchronized(sLock) {
        try {
            JSONStringer json = new JSONStringer()
                .object()
                .key(DATA_INTENT_KEY).value(info.data.toUri(0))
                .key(LAUNCH_INTENT_KEY).value(info.launchIntent.toUri(0))
                .key(NAME_KEY).value(info.name);
            if (info.icon != null) {
                byte[] iconByteArray = ItemInfo.flattenBitmap(info.icon);
                json = json.key(ICON_KEY).value(
                    Base64.encodeToString(
                        iconByteArray, 0, iconByteArray.length, Base64.DEFAULT));
            }
            if (info.iconResource != null) {
                json = json.key(ICON_RESOURCE_NAME_KEY).value(info.iconResource.resourceName);
                json = json.key(ICON_RESOURCE_PACKAGE_NAME_KEY)
                    .value(info.iconResource.packageName);
            }
            json = json.endObject();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            if (DBG) Log.d(TAG, "Adding to APPS_PENDING_INSTALL: " + json);
            addToStringSet(sharedPrefs, editor, APPS_PENDING_INSTALL, json.toString());
            editor.commit();
        } catch (org.json.JSONException e) {
            Log.d(TAG, "Exception when adding shortcut: " + e);
        }
    }
}
 
Example 16
Source Project: egads   Source File: JsonEncoder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void // modifies json_out
toJson(Object object, JSONStringer json_out) throws Exception {
    json_out.object();
    // for each inherited class...
    for (Class c = object.getClass(); c != Object.class; c = c
            .getSuperclass()) {
        // for each member variable... 
        Field[] fields = c.getDeclaredFields();
        for (Field f : fields) {
            // if variable is static/private... skip it
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            if (Modifier.isPrivate(f.getModifiers())) {
                continue;
            }
            Object value = f.get(object);

            // if variable is a complex type... recurse on sub-objects
            if (value instanceof JsonAble) {
                json_out.key(f.getName());
                ((JsonAble) value).toJson(json_out);
                // if variable is an array... recurse on sub-objects
            } else if (value instanceof ArrayList) {
                json_out.key(f.getName());
                json_out.array();
                for (Object e : (ArrayList) value) {
                    toJson(e, json_out);
                }
                json_out.endArray();
                // if variable is a simple type... convert to json
            } else {
                json_out.key(f.getName()).value(value);
            }
        }
    }
    json_out.endObject();
}
 
Example 17
@RequestMapping(value = "/dhusversion", method = RequestMethod.GET)
public String getVersion() throws JSONException
{                
   final String version = DHuS.class.getPackage().getImplementationVersion();
   JSONStringer jstring = new JSONStringer();
   jstring.object().key ("value").value (
      (version==null? "Development Version" : version )).endObject ();
   return jstring.toString ();
}
 
Example 18
@RequestMapping(value = "/version", method = RequestMethod.GET)
public String getVersion() throws JSONException
{                
   final String version = DHuS.class.getPackage().getImplementationVersion();
   JSONStringer jstring = new JSONStringer();
   jstring.object().key ("value").value (
      (version==null? "Development Version" : version )).endObject ();
   return jstring.toString ();
}
 
Example 19
Source Project: LB-Launcher   Source File: PackageInstallerCompatV16.java    License: Apache License 2.0 5 votes vote down vote up
private static String infoToJson(PackageInstallInfo info) {
    String value = null;
    try {
        JSONStringer json = new JSONStringer()
                .object()
                .key(KEY_STATE).value(info.state)
                .key(KEY_PROGRESS).value(info.progress)
                .endObject();
        value = json.toString();
    } catch (JSONException e) {
        Log.e(TAG, "failed to serialize app state update", e);
    }
    return value;
}
 
Example 20
Source Project: android-test   Source File: ElementReference.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toJSONString() {
  try {
    return new JSONStringer().object().key(KEY).value(opaque).endObject().toString();
  } catch (JSONException je) {
    throw new RuntimeException(je);
  }
}
 
Example 21
Source Project: android-test   Source File: WindowReference.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toJSONString() {
  try {
    return new JSONStringer().object().key(KEY).value(opaque).endObject().toString();
  } catch (JSONException je) {
    throw new RuntimeException(je);
  }
}
 
Example 22
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testValueJSONNull() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.value(JSONObject.NULL);
    stringer.endArray();
    assertEquals("[null]", stringer.toString());
}
 
Example 23
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testArray() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.value(false);
    stringer.value(5.0);
    stringer.value(5L);
    stringer.value("five");
    stringer.value(null);
    stringer.endArray();
    assertEquals("[false,5,5,\"five\",null]", stringer.toString());
}
 
Example 24
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testValueObjectMethods() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.value(Boolean.FALSE);
    stringer.value(Double.valueOf(5.0));
    stringer.value(Long.valueOf(5L));
    stringer.endArray();
    assertEquals("[false,5,5]", stringer.toString());
}
 
Example 25
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testKeyValue() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.object();
    stringer.key("a").value(false);
    stringer.key("b").value(5.0);
    stringer.key("c").value(5L);
    stringer.key("d").value("five");
    stringer.key("e").value(null);
    stringer.endObject();
    assertEquals("{\"a\":false," +
            "\"b\":5," +
            "\"c\":5," +
            "\"d\":\"five\"," +
            "\"e\":null}", stringer.toString());
}
 
Example 26
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test what happens when extreme values are emitted. Such values are likely
 * to be rounded during parsing.
 */
public void testNumericRepresentations() throws JSONException {
    if (System.getProperty("os.arch").equals("armv7")) {
      // On armv7, MIN_VALUE is indistinguishable from zero.
      return;
    }
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.value(Long.MAX_VALUE);
    stringer.value(Double.MIN_VALUE);
    stringer.endArray();
    assertEquals("[9223372036854775807,4.9E-324]", stringer.toString());
}
 
Example 27
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testNullKey() {
    try {
        new JSONStringer().object().key(null);
        fail();
    } catch (JSONException e) {
    }
}
 
Example 28
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testRepeatedKey() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.object();
    stringer.key("a").value(true);
    stringer.key("a").value(false);
    stringer.endObject();
    // JSONStringer doesn't attempt to detect duplicates
    assertEquals("{\"a\":true,\"a\":false}", stringer.toString());
}
 
Example 29
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEmptyKey() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.object();
    stringer.key("").value(false);
    stringer.endObject();
    assertEquals("{\"\":false}", stringer.toString()); // legit behaviour!
}
 
Example 30
Source Project: j2objc   Source File: JSONStringerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertEscapedAllWays(String escaped, String original) throws JSONException {
    assertEquals("{\"" + escaped + "\":false}",
            new JSONStringer().object().key(original).value(false).endObject().toString());
    assertEquals("{\"a\":\"" + escaped + "\"}",
            new JSONStringer().object().key("a").value(original).endObject().toString());
    assertEquals("[\"" + escaped + "\"]",
            new JSONStringer().array().value(original).endArray().toString());
    assertEquals("\"" + escaped + "\"", JSONObject.quote(original));
}