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

The following examples show how to use org.json.JSONObject#keys() . 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: KlyphMessenger   File: TagDeserializer.java    License: 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 2
Source Project: FreezeYou   File: BackupUtils.java    License: 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 3
Source Project: blue-marlin   File: QueryUtil.java    License: 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 4
Source Project: xGetter   File: Pstream.java    License: Apache License 2.0 6 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 5
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
@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 7
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 8
Source Project: XmlToJson   File: XmlToJson.java    License: 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 9
@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 10
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 11
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 12
Source Project: Klyph   File: JsonUtil.java    License: 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 13
Source Project: marathonv5   File: BeanToJsonConverter.java    License: 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 14
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 15
Source Project: FreezeYou   File: BackupUtils.java    License: 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 16
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 17
/**
 * 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 18
/**
 * 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 19
Source Project: aurous-app   File: Zipper.java    License: 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 20
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;
}