org.json.JSONStringer Java Examples

The following examples show how to use org.json.JSONStringer. 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: PreUtils.java    From Hook with 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 File: JSONStringerTest.java    From j2objc with 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 #3
Source File: Evaluation.java    From android-test with 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 #4
Source File: AcceptSDKParser.java    From accept-sdk-android with 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 #5
Source File: ModelCodec.java    From android-test with 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 #6
Source File: AcceptSDKParser.java    From accept-sdk-android with 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 #7
Source File: Utils.java    From yawl with 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 #8
Source File: Utils.java    From yawl with 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 #9
Source File: JSONStringerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testMultipleRoots() throws JSONException {
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.endArray();
    try {
        stringer.object();
        fail();
    } catch (JSONException e) {
    }
}
 
Example #10
Source File: AcceptSDKParser.java    From accept-sdk-android with 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 #11
Source File: JSONStringerTest.java    From j2objc with 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 #12
Source File: JsonEncoder.java    From egads with 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 #13
Source File: AcceptSDKParser.java    From accept-sdk-android with 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 File: JSONStringerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testJSONArrayAsValue() throws JSONException {
    JSONArray array = new JSONArray();
    array.put(false);
    JSONStringer stringer = new JSONStringer();
    stringer.array();
    stringer.value(array);
    stringer.endArray();
    assertEquals("[[false]]", stringer.toString());
}
 
Example #15
Source File: NodeArchiveServiceRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #16
Source File: NodeArchiveServiceRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #17
Source File: JSONUtils.java    From orion.server with 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 #18
Source File: Util.java    From AutoInteraction-Library with 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 #19
Source File: JSONStringerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testMaxDepthWithArrayValue() throws JSONException {
    JSONArray array = new JSONArray();
    array.put(false);

    JSONStringer stringer = new JSONStringer();
    for (int i = 0; i < 20; i++) {
        stringer.array();
    }
    stringer.value(array);
    for (int i = 0; i < 20; i++) {
        stringer.endArray();
    }
    assertEquals("[[[[[[[[[[[[[[[[[[[[[false]]]]]]]]]]]]]]]]]]]]]", stringer.toString());
}
 
Example #20
Source File: JSONStringerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testNullKey() {
    try {
        new JSONStringer().object().key(null);
        fail();
    } catch (JSONException e) {
    }
}
 
Example #21
Source File: JSONStringerTest.java    From j2objc with 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 #22
Source File: JSONStringerTest.java    From j2objc with 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 #23
Source File: JSONStringerTest.java    From j2objc with 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 #24
Source File: JSONStringerTest.java    From j2objc with 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 #25
Source File: JSONStringerTest.java    From j2objc with 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 #26
Source File: WindowReference.java    From android-test with 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 #27
Source File: ElementReference.java    From android-test with 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 #28
Source File: PackageInstallerCompatV16.java    From LB-Launcher with 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 #29
Source File: StubVersionController.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #30
Source File: OwcVersionController.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 ();
}