本文整理匯總了Java中org.json.JSONObject.remove方法的典型用法代碼示例。如果您正苦於以下問題:Java JSONObject.remove方法的具體用法?Java JSONObject.remove怎麽用?Java JSONObject.remove使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.json.JSONObject
的用法示例。
在下文中一共展示了JSONObject.remove方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: removeNullFields
import org.json.JSONObject; //導入方法依賴的package包/類
/**
* Remove 'null' fields from a JSONObject. This method calls itself recursively until all the
* fields have been looked at.
* TODO(mlamouri): move to some util class?
*/
private static void removeNullFields(Object object) throws JSONException {
if (object instanceof JSONArray) {
JSONArray array = (JSONArray) object;
for (int i = 0; i < array.length(); ++i) removeNullFields(array.get(i));
} else if (object instanceof JSONObject) {
JSONObject json = (JSONObject) object;
JSONArray names = json.names();
if (names == null) return;
for (int i = 0; i < names.length(); ++i) {
String key = names.getString(i);
if (json.isNull(key)) {
json.remove(key);
} else {
removeNullFields(json.get(key));
}
}
}
}
示例2: getURLDetails
import org.json.JSONObject; //導入方法依賴的package包/類
public static JSONObject getURLDetails(String shortURL) {
JSONObject json = new JSONObject();
try {
Record record = db.readKey(Constants.URLS, shortURL);
json.append(Constants.SHORT_URL, shortURL);
json.append(Constants.LONG_URL, record.getString(Constants.LONG_URL));
json.append(Constants.HIT_COUNT, record.getLong(Constants.HIT_COUNT));
Date date = new Date(record.getLong(Constants.TIMESTAMP));
DateFormat format = new SimpleDateFormat( "MM/dd/yyyy HH:mm:ss");
json.append(Constants.TIMESTAMP, format.format(date));
} catch (Exception e) {
e.printStackTrace();
try {
json.append(Constants.MESSAGE, Constants.INVALID_SHORT_URL);
json.remove(Constants.SHORT_URL);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return json;
}
示例3: removeUnusedProperties
import org.json.JSONObject; //導入方法依賴的package包/類
/**
* Removes unused properties of the specified article.
* <p>
* Remains the following properties:
* <ul>
* <li>{@link Article#ARTICLE_TITLE article title}</li>
* <li>{@link Article#ARTICLE_PERMALINK article permalink}</li>
* </ul>
* </p>
*
* @param article
* the specified article
* @see #removeUnusedProperties(java.util.List)
*/
public void removeUnusedProperties(final JSONObject article) {
article.remove(Keys.OBJECT_ID);
article.remove(Article.ARTICLE_AUTHOR_EMAIL);
article.remove(Article.ARTICLE_ABSTRACT);
article.remove(Article.ARTICLE_COMMENT_COUNT);
article.remove(Article.ARTICLE_CONTENT);
article.remove(Article.ARTICLE_CREATE_DATE);
article.remove(Article.ARTICLE_TAGS_REF);
article.remove(Article.ARTICLE_UPDATE_DATE);
article.remove(Article.ARTICLE_VIEW_COUNT);
article.remove(Article.ARTICLE_RANDOM_DOUBLE);
article.remove(Article.ARTICLE_IS_PUBLISHED);
article.remove(Article.ARTICLE_PUT_TOP);
article.remove(Article.ARTICLE_HAD_BEEN_PUBLISHED);
}
示例4: onJsPrompt
import org.json.JSONObject; //導入方法依賴的package包/類
public boolean onJsPrompt(WebView webView, String str, String str2, String str3, JsPromptResult jsPromptResult) {
if ("ekv".equals(str2)) {
try {
JSONObject jSONObject = new JSONObject(str3);
Map hashMap = new HashMap();
String str4 = (String) jSONObject.remove("id");
int intValue = jSONObject.isNull(DownloadVideoTable.COLUMN_DURATION) ? 0 : ((Integer) jSONObject.remove(DownloadVideoTable.COLUMN_DURATION)).intValue();
Iterator keys = jSONObject.keys();
while (keys.hasNext()) {
String str5 = (String) keys.next();
hashMap.put(str5, jSONObject.getString(str5));
}
MobclickAgent.getAgent().a(this.b.a, str4, hashMap, (long) intValue);
} catch (Exception e) {
e.printStackTrace();
}
} else if (!NotificationCompat.CATEGORY_EVENT.equals(str2)) {
return this.a.onJsPrompt(webView, str, str2, str3, jsPromptResult);
} else {
try {
JSONObject jSONObject2 = new JSONObject(str3);
String optString = jSONObject2.optString("label");
if ("".equals(optString)) {
optString = null;
}
MobclickAgent.getAgent().a(this.b.a, jSONObject2.getString("tag"), optString, (long) jSONObject2.optInt(DownloadVideoTable.COLUMN_DURATION), 1);
} catch (Exception e2) {
}
}
jsPromptResult.confirm();
return true;
}
示例5: readInternal
import org.json.JSONObject; //導入方法依賴的package包/類
protected <R extends Object> R readInternal(final DocumentDbPersistentEntity<?> entity, Class<R> type,
final Document sourceDocument) {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
final DocumentDbPersistentProperty idProperty = entity.getIdProperty();
final Object idValue = sourceDocument.getId();
final JSONObject jsonObject = new JSONObject(sourceDocument.toJson());
if (idProperty != null) {
// Replace the key id to the actual id field name in domain
jsonObject.remove("id");
jsonObject.put(idProperty.getName(), idValue);
}
return objectMapper.readValue(jsonObject.toString(), type);
} catch (IOException e) {
throw new IllegalStateException("Failed to read the source document " + sourceDocument.toJson()
+ " to target type " + type, e);
}
}
示例6: removeData
import org.json.JSONObject; //導入方法依賴的package包/類
public void removeData(String path, String key) {
createFile(path);
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(KAKAOBOT_HOME, path)));
String line;
StringBuilder result = new StringBuilder();
while((line = reader.readLine()) != null) {
result.append(line);
result.append("\n");
}
JSONObject json = new JSONObject(result.toString() + "");
json.remove(key);
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(KAKAOBOT_HOME, path)));
writer.write(json.toString());
reader.close();
writer.close();
} catch(IOException err) {
err.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
示例7: toJSONClone
import org.json.JSONObject; //導入方法依賴的package包/類
/**
* An action is backed with a JSON data structure. That can be retrieved here.
* @return the json structure of the action
*/
public JSONObject toJSONClone() {
JSONObject j = new JSONObject(true);
this.json.keySet().forEach(key -> j.put(key, this.json.get(key))); // make a clone
if (j.has("expression")) {
j.remove("phrases");
j.remove("select");
}
return j;
}
示例8: handle
import org.json.JSONObject; //導入方法依賴的package包/類
@Override
public void handle(RoutingContext ctx) {
String clientId = UserManager.getEncryptedIdFromSession(ctx);
JSONObject response = UserManager.getUserInfo(clientId);
response.remove("id");
ctx.response().setStatusCode(200);
ctx.response().end(response.toString());
ctx.response().close();
}
示例9: getDestination
import org.json.JSONObject; //導入方法依賴的package包/類
public URL getDestination(Object request, Map<String,String> headers) {
String requestUrl = headers.get(Listener.METAINFO_REQUEST_URL);
if (StringHelper.isEmpty(requestUrl) || !requestUrl.contains("com/centurylink/mdw/slack"))
return null;
try {
String callbackId = null;
JSONObject message = new JSONObject(request.toString());
if (requestUrl.endsWith("event")) {
SlackEvent event = new SlackEvent(message);
callbackId = event.getCallbackId();
}
else {
SlackRequest slackReq = new SlackRequest(message);
callbackId = slackReq.getCallbackId();
}
if (callbackId == null) {
logger.debug("Received message for Slack routing, but missing callback_id");
return null;
}
else {
String[] array = callbackId.split("://");
if (array.length < 2 || array[1].indexOf("/") < 0) {
logger.debug("Received message for Slack routing, but malformed callback_id");
return null;
}
String instance = array[1].substring(0, array[1].indexOf("/"));
message.remove("token");
request = message.toString();
return buildURL(headers, instance);
}
}
catch (Throwable e) {
logger.exception(null, "Received Slack message for routing, but could not parse out destination", e);
}
return null;
}
示例10: update
import org.json.JSONObject; //導入方法依賴的package包/類
/**
* Update configurations for a list of keys
*
* @param keys - list of config key to migrate
*/
public static boolean update(List<String> keys) {
try {
Map<String, String> conf = readConfig(keys);
if (conf == null) {
return false;
}
List<String> confSystem = new ArrayList<>(0);
//process
for (String domainId : conf.keySet()) {
xLog.info("Parsing config for domain {0}", domainId);
JSONObject config = new JSONObject(conf.get(domainId));
JSONObject inventory = (JSONObject) config.get("invntry");
JSONObject optmz = (JSONObject) config.get("optmz");
String compute = (String) optmz.get("compute");
if (inventory.has("cr") || inventory.has("dispcr")) {
xLog.info("New configuration already set for: {0}", domainId);
confSystem.add(domainId);
continue;
}
if (optmz.has("compute-crfreqs")) {
optmz.remove("compute-crfreqs");
}
if (inventory.has("manualcr")) {
String manualcr = (String) inventory.get("manualcr");
inventory.put("cr", "0");
inventory.put("manualcrfreq", manualcr);
inventory.put("dispcr", true);
inventory.put("dcrfreq", manualcr);
optmz.put("compute", "-1");
inventory.remove("manualcr");
xLog.info("Configuration set for manualcr: {0}" + domainId);
} else if ("0".equals(compute)) {
inventory.put("cr", "1");
inventory.put("dispcr", false);
optmz.put("compute", "-1");
xLog.info("Configuration set for Automatic: {0}" + domainId);
} else if ("100".equals(compute) || "200".equals(compute)) {
inventory.put("cr", "1");
inventory.put("dispcr", false);
xLog.info("Configuration set for Demand forecast/OOQ: {0}" + domainId);
} else if ("-1".equals(compute)) {
inventory.put("cr", "-1");
inventory.put("dispcr", false);
xLog.info("Configuration set for forecasting as NONE: {0}" + domainId);
}
inventory.put("showpr", false);
config.put("invntry", inventory);
config.put("optmz", optmz);
conf.put(domainId, String.valueOf(config));
}
//update
ps = connection.prepareStatement(CONFIG_UPDATE_QUERY);
for (String confKeys : conf.keySet()) {
if (!confSystem.contains(confKeys)) {
ps.setString(1, conf.get(confKeys));
ps.setString(2, confKeys);
ps.addBatch();
}
}
int[] count = ps.executeBatch();
xLog.info("{0} domains updated out of {1}", count.length, conf.size());
} catch (Exception e) {
xLog.warn("Error in updating configuration: " + e);
return false;
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException ignored) {
xLog.warn("Exception while closing prepared statement", ignored);
}
}
}
return true;
}
示例11: buildJson
import org.json.JSONObject; //導入方法依賴的package包/類
private String buildJson(JSONObject jsonObject, String eventConfigJson, Boolean action)
throws ServiceException {
if (jsonObject == null) {
return "";
}
try {
JSONObject eventJSON = new JSONObject(eventConfigJson);
Iterator<String> iteratorNew = jsonObject.keys();
Iterator<String> iteratorConfig = eventJSON.keys();
while (iteratorNew.hasNext()) {
String key = iteratorNew.next();
JSONArray obj = null;
while (iteratorConfig.hasNext()) {
if (key.equalsIgnoreCase(iteratorConfig.next())) {
obj = eventJSON.getJSONArray(key);
break;
}
}
if (obj != null && obj.length() > 0) {
obj = buildJSONArray(obj, jsonObject, key, action);
eventJSON.remove(key);
eventJSON.put(key, obj);
} else {
eventJSON.put(key, jsonObject.get(key));
}
}
return eventJSON.toString();
} catch (JSONException e) {
throw new ServiceException("Error while building JSON object for notifications", e);
}
}
示例12: testUpdateRule
import org.json.JSONObject; //導入方法依賴的package包/類
public void testUpdateRule() throws Exception
{
JSONObject jsonRule = createRule(testNodeRef);
String ruleId = jsonRule.getJSONObject("data").getString("id");
Response getResponse = sendRequest(new GetRequest(formateRuleUrl(testNodeRef, ruleId)), 200);
JSONObject before = new JSONObject(getResponse.getContentAsString());
// do some changes
before.put("description", "this is modified description for test_rule");
// do some changes for action object
JSONObject beforeAction = before.getJSONObject("action");
// no changes for actions list
beforeAction.remove("actions");
// clear conditions
beforeAction.put("conditions", new JSONArray());
Response putResponse = sendRequest(new PutRequest(formateRuleUrl(testNodeRef, ruleId), before.toString(), "application/json"), 200);
JSONObject after = new JSONObject(putResponse.getContentAsString());
// sent and retrieved objects should be the same (except ids and urls)
// this means that all changes was saved
checkUpdatedRule(before, after);
}
示例13: onJsPrompt
import org.json.JSONObject; //導入方法依賴的package包/類
public boolean onJsPrompt(WebView webView, String str, String str2, String str3,
JsPromptResult jsPromptResult) {
if ("ekv".equals(str2)) {
try {
JSONObject jSONObject = new JSONObject(str3);
Map hashMap = new HashMap();
String str4 = (String) jSONObject.remove("id");
int intValue = jSONObject.isNull(SportRecordDao.DURATION) ? 0 : ((Integer)
jSONObject.remove(SportRecordDao.DURATION)).intValue();
Iterator keys = jSONObject.keys();
while (keys.hasNext()) {
String str5 = (String) keys.next();
hashMap.put(str5, jSONObject.getString(str5));
}
MobclickAgent.getAgent().a(this.b.a, str4, hashMap, (long) intValue);
} catch (Exception e) {
e.printStackTrace();
}
} else if (!"event".equals(str2)) {
return this.a.onJsPrompt(webView, str, str2, str3, jsPromptResult);
} else {
try {
JSONObject jSONObject2 = new JSONObject(str3);
String optString = jSONObject2.optString("label");
if ("".equals(optString)) {
optString = null;
}
MobclickAgent.getAgent().a(this.b.a, jSONObject2.getString(DownloadService
.EXTRA_TAG), optString, (long) jSONObject2.optInt(SportRecordDao
.DURATION), 1);
} catch (Exception e2) {
}
}
jsPromptResult.confirm();
return true;
}
示例14: action
import org.json.JSONObject; //導入方法依賴的package包/類
public void action(final Event<JSONObject> event) throws EventException {
final JSONObject data = event.getData();
logger.debug("Processing an event[type={}, data={}] in listener[className={}]", event.getType(), data,
RhythmArticleSender.class);
try {
final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
logger.debug("Ignores post article[title={}] to Rhythm",
originalArticle.getString(Article.ARTICLE_TITLE));
return;
}
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
throw new EventException("Not found preference");
}
if (!StringUtils.isBlank(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
return;
}
if (Latkes.getServePath().contains("localhost")) {
logger.info("Solo runs on local server, so should not send this article[id={}, title={}] to Rhythm",
originalArticle.getString(Keys.OBJECT_ID), originalArticle.getString(Article.ARTICLE_TITLE));
return;
}
final HTTPRequest httpRequest = new HTTPRequest();
httpRequest.setURL(ADD_ARTICLE_URL);
httpRequest.setRequestMethod(RequestMethod.POST);
final JSONObject requestJSONObject = new JSONObject();
final JSONObject article = new JSONObject();
article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
article.put(Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
article.put(Article.ARTICLE_CREATE_DATE,
((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));
// Removes this property avoid to persist
originalArticle.remove(Common.POST_TO_COMMUNITY);
requestJSONObject.put(Article.ARTICLE, article);
requestJSONObject.put(Common.BLOG_VERSION, SoloConstant.VERSION);
requestJSONObject.put(Common.BLOG, "B3log Solo");
requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
requestJSONObject.put("blogHost", Latkes.getServePath());
requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());
httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));
urlFetchService.fetchAsync(httpRequest);
} catch (final Exception e) {
logger.error("Sends an article to Rhythm error: {}", e.getMessage());
}
logger.debug("Sent an article to Rhythm");
}
示例15: action
import org.json.JSONObject; //導入方法依賴的package包/類
public void action(final Event<JSONObject> event) throws EventException {
final JSONObject data = event.getData();
logger.debug("Processing an event[type={}, data={}] in listener[className={}]", event.getType(), data,
RhythmArticleUpdater.class);
try {
final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
logger.debug("Ignores post article[title={}] to Rhythm",
originalArticle.getString(Article.ARTICLE_TITLE));
return;
}
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
throw new EventException("Not found preference");
}
if (!StringUtils.isBlank(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
return;
}
if (Latkes.getServePath().contains("localhost")) {
logger.info("Solo runs on local server, so should not send this article[id={}, title={}] to Rhythm",
originalArticle.getString(Keys.OBJECT_ID), originalArticle.getString(Article.ARTICLE_TITLE));
return;
}
final HTTPRequest httpRequest = new HTTPRequest();
httpRequest.setURL(UPDATE_ARTICLE_URL);
httpRequest.setRequestMethod(RequestMethod.PUT);
final JSONObject requestJSONObject = new JSONObject();
final JSONObject article = new JSONObject();
article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
article.put(Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
article.put(Article.ARTICLE_CREATE_DATE,
((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));
// Removes this property avoid to persist
originalArticle.remove(Common.POST_TO_COMMUNITY);
requestJSONObject.put(Article.ARTICLE, article);
requestJSONObject.put(Common.BLOG_VERSION, SoloConstant.VERSION);
requestJSONObject.put(Common.BLOG, "B3log Solo");
requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
requestJSONObject.put("blogHost", Latkes.getServerHost() + ":" + Latkes.getServerPort());
requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());
httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));
urlFetchService.fetchAsync(httpRequest);
} catch (final Exception e) {
logger.error("Sends an article to Rhythm error: {}", e.getMessage());
}
logger.debug("Sent an article to Rhythm");
}