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

The following examples show how to use org.json.JSONObject#keys() . 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: Pstream.java    From xGetter with Apache License 2.0 9 votes vote down vote up
private static ArrayList<XModel> parseVideo(String string){
    ArrayList<XModel> xModels = new ArrayList<>();
    try {
        JSONObject object = new JSONObject(string);
        Iterator<String> keys = object.keys();
        while (keys.hasNext()){
            String key = keys.next();
            XModel xModel = new XModel();
            xModel.setQuality(key+"p");
            xModel.setUrl(object.getString(key));
            xModels.add(xModel);
        }
        return xModels;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 2
Source File: TagDeserializer.java    From KlyphMessenger with MIT License 6 votes vote down vote up
public Map<String, List<Tag>> deserializeMap(JSONObject data)
{
	Map<String, List<Tag>> map = new Hashtable<String, List<Tag>>();

	if (data != null)
	{
		for (Iterator iterator = data.keys(); iterator.hasNext();)
		{
			String key = (String) iterator.next();

			JSONArray tags = data.optJSONArray(key);
			map.put(key, deserializeArray(tags, Tag.class));
		}
	}

	return map;
}
 
Example 3
Source File: ImageResolutionTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testJson(){
    JSONObject reference = new JSONObject();

    try{
        reference.put(ImageResolution.KEY_RESOLUTION_HEIGHT, Test.GENERAL_INT);
        reference.put(ImageResolution.KEY_RESOLUTION_WIDTH, Test.GENERAL_INT);

        JSONObject underTest = msg.serializeJSON();
        assertEquals(Test.MATCH, reference.length(), underTest.length());

        Iterator<?> iterator = reference.keys();
        while(iterator.hasNext()){
            String key = (String) iterator.next();
            assertEquals(Test.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
        }
    } catch(JSONException e){
    	fail(Test.JSON_FAIL);
    }
}
 
Example 4
Source File: FirebaseAnalyticsPlugin.java    From cordova-plugin-firebase-analytics with MIT License 6 votes vote down vote up
@CordovaMethod
private void logEvent(String name, JSONObject params, CallbackContext callbackContext) throws JSONException {
    Bundle bundle = new Bundle();
    Iterator<String> it = params.keys();

    while (it.hasNext()) {
        String key = it.next();
        Object value = params.get(key);

        if (value instanceof String) {
            bundle.putString(key, (String)value);
        } else if (value instanceof Integer) {
            bundle.putInt(key, (Integer)value);
        } else if (value instanceof Double) {
            bundle.putDouble(key, (Double)value);
        } else if (value instanceof Long) {
            bundle.putLong(key, (Long)value);
        } else {
            Log.w(TAG, "Value for key " + key + " not one of (String, Integer, Double, Long)");
        }
    }

    this.firebaseAnalytics.logEvent(name, bundle);

    callbackContext.success();
}
 
Example 5
Source File: TouchCoordTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testJson() {
	JSONObject reference = new JSONObject();

	try {
		reference.put(TouchCoord.KEY_X, Test.GENERAL_INT);
		reference.put(TouchCoord.KEY_Y, Test.GENERAL_INT);

		JSONObject underTest = msg.serializeJSON();
		assertEquals(Test.MATCH, reference.length(), underTest.length());

		Iterator<?> iterator = reference.keys();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			assertEquals(Test.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
		}
	} catch (JSONException e) {
		fail(Test.JSON_FAIL);
	}
}
 
Example 6
Source File: QueryUtil.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method converts a json object to a map.
 *
 * @param object
 * @return
 * @throws JSONException
 */
public static Map<String, Object> toMap(JSONObject object) throws JSONException
{
    Map<String, Object> map = new HashMap<>();
    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext())
    {
        String key = keysItr.next();
        Object value = object.get(key);

        if (value instanceof JSONArray)
        {
            value = toList((JSONArray) value);
        }

        if (value instanceof JSONObject)
        {
            value = toMap((JSONObject) value);
        }

        map.put(key, value);
    }
    return map;
}
 
Example 7
Source File: BackupUtils.java    From FreezeYou with Apache License 2.0 6 votes vote down vote up
private static void importIntSharedPreferencesFromProcessedJSONObject(
        Context context, Activity activity, JSONObject generalSettingsIntJSONObject,
        SharedPreferences defSP, AppPreferences appPreferences) {
    Iterator<String> it = generalSettingsIntJSONObject.keys();
    String s;
    while (it.hasNext()) {
        s = it.next();
        switch (s) {
            case "onClickFunctionStatus":
            case "sortMethodStatus":
                importIntSharedPreference(
                        context, activity, generalSettingsIntJSONObject, defSP, appPreferences, s);
                break;
            default:
                break;
        }
    }
}
 
Example 8
Source File: BeanToJsonConverter.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> convertJsonObject(JSONObject jsonObject) {
    Map<String, Object> toReturn = new HashMap<String, Object>();
    Iterator<?> allKeys = jsonObject.keys();
    while (allKeys.hasNext()) {
        String key = (String) allKeys.next();

        try {
            toReturn.put(key, convertUnknownObjectFromJson(jsonObject.get(key)));
        } catch (JSONException e) {
            throw new IllegalStateException("Unable to access key: " + key, e);
        }
    }
    return toReturn;
}
 
Example 9
Source File: JsonUtil.java    From Klyph with MIT License 5 votes vote down vote up
static Set<String> jsonObjectKeySet(JSONObject jsonObject) {
    HashSet<String> result = new HashSet<String>();

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        result.add(keys.next());
    }

    return result;
}
 
Example 10
Source File: VrHelpItemTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testJson() {
	JSONObject reference = new JSONObject();

	try {	        
		reference.put(VrHelpItem.KEY_IMAGE, Test.JSON_IMAGE);
		reference.put(VrHelpItem.KEY_TEXT, Test.GENERAL_STRING);
		reference.put(VrHelpItem.KEY_POSITION, Test.GENERAL_INT);

		JSONObject underTest = msg.serializeJSON();
		assertEquals(Test.MATCH, reference.length(), underTest.length());

		Iterator<?> iterator = reference.keys();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			
			if(key.equals(VrHelpItem.KEY_IMAGE)){
               	JSONObject objectEquals = JsonUtils.readJsonObjectFromJsonObject(reference, key);
               	JSONObject testEquals = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
               	Hashtable<String, Object> hashReference = JsonRPCMarshaller.deserializeJSONObject(objectEquals);
               	Hashtable<String, Object> hashTest = JsonRPCMarshaller.deserializeJSONObject(testEquals);
               	
                assertTrue(Test.TRUE, Validator.validateImage(new Image(hashReference), new Image(hashTest)));
            } else {
				assertEquals(Test.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
            }
		}
	} catch (JSONException e) {
		fail(Test.JSON_FAIL);
	}
}
 
Example 11
Source File: BackupUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
private static void importOneKeyListsFromProcessedJSONObject(
        Context context, JSONObject oneKeyListJSONObject, AppPreferences appPreferences) {
    Iterator<String> it = oneKeyListJSONObject.keys();
    String s;
    while (it.hasNext()) {
        s = it.next();
        switch (s) {
            case "okff":
                appPreferences.put(
                        context.getString(R.string.sAutoFreezeApplicationList),
                        oneKeyListJSONObject.optString("okff"));
                break;
            case "okuf":
                appPreferences.put(
                        context.getString(R.string.sOneKeyUFApplicationList),
                        oneKeyListJSONObject.optString("okuf"));
                break;
            case "foq":
                appPreferences.put(
                        context.getString(R.string.sFreezeOnceQuit),
                        oneKeyListJSONObject.optString("foq"));
                break;
            default:
                break;
        }
    }
}
 
Example 12
Source File: ColumnMapping.java    From db with GNU Affero General Public License v3.0 5 votes vote down vote up
public ColumnMapping(JSONObject jsonObject) throws JSONException {
    this.index = new AtomicInteger(jsonObject.getInt("index"));
    JSONObject mapJson = jsonObject.getJSONObject("map");
    Iterator<String> keysIterator = mapJson.keys();
    while (keysIterator.hasNext()) {
        String viewableName = keysIterator.next();
        String internalName = mapJson.getString(viewableName);
        viewableNameMap.put(viewableName, internalName);
        internalNameMap.put(internalName, viewableName);
    }
}
 
Example 13
Source File: ConversionJSONInput.java    From equalize-xpi-modules with MIT License 5 votes vote down vote up
private ArrayList<Field> parseJSON(JSONObject jo) {
	ArrayList<Field> arr = new ArrayList<Field>();
	Iterator<String> keyIter = jo.keys();
	while(keyIter.hasNext()) {
		String keyName = keyIter.next();
		Object parsedObj = parseJSON(jo.get(keyName));
		arr.add(new Field(keyName, parsedObj));
	}
	return arr;
}
 
Example 14
Source File: ChatEmoteManager.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
private Emote ToFFZ(JSONObject emoteObject) throws JSONException {
    final String EMOTE_NAME = "name";
    final String EMOTE_URLS = "urls";

    JSONObject urls = emoteObject.getJSONObject(EMOTE_URLS);
    HashMap<Integer, String> urlMap = new HashMap<>();
    for (Iterator<String> iterator = urls.keys(); iterator.hasNext();) {
        String key = iterator.next();
        urlMap.put(Integer.parseInt(key), "https:" + urls.getString(key));
    }

    return Emote.FFZ(emoteObject.getString(EMOTE_NAME), urlMap);
}
 
Example 15
Source File: GosScheduleSiteTool.java    From Gizwits-SmartBuld_Android with MIT License 5 votes vote down vote up
/**
 * Description:
 * 
 * @param jo
 * @return
 * @throws JSONException
 */
protected ConcurrentHashMap<String, Object> getDateFromJsonObject(JSONObject jo) throws JSONException {
	ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();
	JSONObject date = jo.optJSONArray("task").getJSONObject(0).optJSONObject("attrs");
	Iterator it = date.keys();
	// 遍历jsonObject数据,添加到Map对象
	while (it.hasNext()) {
		String key = String.valueOf(it.next());
		map.put(key, date.get(key));
	}
	return map;
}
 
Example 16
Source File: CacheResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@POST
@Path("/clean-datasets")
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteDatasets(String body) {
	logger.debug("IN");

	try {
		IDataSetDAO dataSetDAO = DAOFactory.getDataSetDAO();
		dataSetDAO.setUserProfile(getUserProfile());

		JSONObject jsonBody = new JSONObject(body);
		Iterator<String> it = jsonBody.keys();
		while (it.hasNext()) {
			String label = it.next();
			logger.debug("Dataset with label [" + label + "] must be deleted from cache.");
			IDataSet dataSet = dataSetDAO.loadDataSetByLabel(label);

			String params = jsonBody.optString(label, null);
			logger.debug("Dataset with label [" + label + "] has the following parameters [" + params + "].");

			Map<String, String> parametersValues = DataSetUtilities.getParametersMap(params);
			dataSet.setParametersMap(parametersValues);
			dataSet.resolveParameters();
			ICache cache = CacheFactory.getCache(SpagoBICacheConfiguration.getInstance());
			if (cache.delete(dataSet)) {
				logger.debug("Dataset with label [" + label + "] found in cache and deleted.");
			}
		}
	} catch (Exception e) {
		throw new SpagoBIServiceException(this.request.getPathInfo(),
				"An unexpected error occurred while deleting datasets from cache (deleteItem REST service)", e);
	}
	return Response.ok().build();
}
 
Example 17
Source File: JSONUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 5 votes vote down vote up
/**
 * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value
 *
 * @param sourceObj key-value pairs json
 * @return <ul>
 *         <li>if sourceObj is null, return null</li>
 *         <li>else parse entry one by one</li>
 *         </ul>
 */
@SuppressWarnings("rawtypes")
public static Map<String, String> parseKeyAndValueToMap(JSONObject sourceObj) {
    if (sourceObj == null) {
        return null;
    }

    Map<String, String> keyAndValueMap = new HashMap<String, String>();
    for (Iterator iter = sourceObj.keys(); iter.hasNext();) {
        String key = (String)iter.next();
        keyAndValueMap.put(key, getString(sourceObj, key, ""));
    }
    return keyAndValueMap;
}
 
Example 18
Source File: Zipper.java    From aurous-app with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Write a JSON object.
 *
 * @param jsonobject
 *            The JSONObject to be written.
 * @throws JSONException
 */
private void write(final JSONObject jsonobject) throws JSONException {

	// JSONzip has two encodings for objects: Empty Objects (zipEmptyObject)
	// and
	// non-empty objects (zipObject).

	boolean first = true;
	final Iterator<String> keys = jsonobject.keys();
	while (keys.hasNext()) {
		if (probe) {
			log();
		}
		final Object key = keys.next();
		if (key instanceof String) {
			if (first) {
				first = false;
				write(zipObject, 3);
			} else {
				one();
			}
			writeName((String) key);
			final Object value = jsonobject.get((String) key);
			if (value instanceof String) {
				zero();
				writeString((String) value);
			} else {
				one();
				writeValue(value);
			}
		}
	}
	if (first) {
		write(zipEmptyObject, 3);
	} else {
		zero();
	}
}
 
Example 19
Source File: XmlToJson.java    From XmlToJson with Apache License 2.0 5 votes vote down vote up
private void format(JSONObject jsonObject, StringBuilder builder, String indent) {
    Iterator<String> keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        builder.append(indent);
        builder.append(mIndentationPattern);
        builder.append("\"");
        builder.append(key);
        builder.append("\": ");
        Object value = jsonObject.opt(key);
        if (value instanceof JSONObject) {
            JSONObject child = (JSONObject) value;
            builder.append(indent);
            builder.append("{\n");
            format(child, builder, indent + mIndentationPattern);
            builder.append(indent);
            builder.append(mIndentationPattern);
            builder.append("}");
        } else if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            formatArray(array, builder, indent + mIndentationPattern);
        } else {
            formatValue(value, builder);
        }
        if (keys.hasNext()) {
            builder.append(",\n");
        } else {
            builder.append("\n");
        }
    }
}
 
Example 20
Source File: DeliciousURLExtractor.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
private boolean extract(final Topic topic) throws ExtractionFailure, TopicMapException
{
    ArrayList<String> urlList = new ArrayList<String>();
    
    for(Locator l : topic.getSubjectIdentifiers())
    {
        urlList.add(l.toString());
    }
    
    if(topic.getSubjectLocator() != null)
        urlList.add(topic.getSubjectLocator().toString());
    log("Found " + urlList.size() + " url(s) to check.");
    final JSONArray result = doRequest(urlList);
    
    if(result.length() == 0)
    {
        log("No results available.");
        return false;
    }
    
    Topic deliciousT = getDeliciousClass(currentMap);
    Topic tagT = FlickrUtils.createTopic(currentMap, "delicious tag", deliciousT);
    Topic tagAssoc = FlickrUtils.createTopic(currentMap, "describes", deliciousT);
    Topic tagTargetT = FlickrUtils.createTopic(currentMap, "descriptee", deliciousT);
    
    boolean success = false;
    
    for(int i = 0; i < result.length(); ++i)
    {
        final JSONObject resultObj = result.optJSONObject(i);
        if(resultObj == null)
            throw new RequestFailure("Unable to get inner object");

        final JSONObject tagsObj = resultObj.optJSONObject("top_tags");
        if(tagsObj == null)
        {
            log("No results for url[" + i + "]");
            continue;
        }

        log("Extracting tags");
        for(String s : new Iterable<String>() { public Iterator<String> iterator() { return tagsObj.keys(); }})
        {
            log("Extracting tag " + s);
            Topic tag = FlickrUtils.createRaw(currentMap, "http://delicious.com/tag/" + url(s), " (delicious tag)", s, tagT);
            FlickrUtils.createAssociation(currentMap, tagAssoc, new Topic[] { tag, topic }, new Topic[]{tagT, tagTargetT});
        }
        success = true;
    }
    
    return success;
}