org.json.JSONObject.optString()方法的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(15.5k)|赞(0)|评价(0)|浏览(490)

本文整理了Java中org.json.JSONObject.optString()方法的一些代码示例,展示了JSONObject.optString()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JSONObject.optString()方法的具体详情如下:
包路径:org.json.JSONObject
类名称:JSONObject
方法名:optString

JSONObject.optString介绍

[英]Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.
[中]返回按名称映射的值(如果存在),必要时强制该值。如果不存在此类映射,则返回空字符串。

代码示例

代码示例来源:origin: facebook/facebook-android-sdk

private AppEvent(
    String jsonString,
    boolean isImplicit,
    String checksum) throws JSONException {
  jsonObject = new JSONObject(jsonString);
  this.isImplicit = isImplicit;
  this.name = jsonObject.optString(Constants.EVENT_NAME_EVENT_KEY);
  this.checksum = checksum;
}

代码示例来源:origin: facebook/facebook-android-sdk

public ParameterComponent(final JSONObject component) throws JSONException {
    name = component.getString(PARAMETER_NAME_KEY);
    value = component.optString(PARAMETER_VALUE_KEY);

    ArrayList<PathComponent> pathComponents = new ArrayList<>();
    JSONArray jsonPathArray = component.optJSONArray(PARAMETER_PATH_KEY);
    if (null != jsonPathArray) {
      for (int i = 0; i < jsonPathArray.length(); i++) {
        PathComponent pathComponent = new PathComponent((jsonPathArray.getJSONObject(i)));
        pathComponents.add(pathComponent);
      }
    }
    path = pathComponents;
    pathType = component.optString(Constants.EVENT_MAPPING_PATH_TYPE_KEY,
        Constants.PATH_TYPE_ABSOLUTE);

  }
}

代码示例来源:origin: facebook/facebook-android-sdk

public List<AppLink> getAppLinks() {
  List<AppLink> appLinks = new ArrayList<>();
  JSONObject appLinkJson = jsonData.optJSONObject(APP_LINKS);
  if (appLinkJson != null) {
    JSONArray appArray = appLinkJson.optJSONArray("android");
    if (appArray != null) {
      int length = appArray.length();
      for (int i = 0; i < length; i++) {
        JSONObject linkJson = appArray.optJSONObject(i);
        if (linkJson != null) {
          String appName = linkJson.optString("app_name");
          Intent intent = new Intent(Intent.ACTION_VIEW);
          String packageName = linkJson.optString("package");
          String className = linkJson.optString("class");
          if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
            intent.setClassName(packageName, className);
          }
          String url = linkJson.optString("url");
          if (url != null) {
            intent.setData(Uri.parse(url));
          }
          appLinks.add(new AppLink(appName, intent));
        }
      }
    }
  }
  return appLinks;
}

代码示例来源:origin: facebook/facebook-android-sdk

ActionType type = ActionType.valueOf(mapping.getString("event_type").toUpperCase(Locale.ENGLISH));
String appVersion = mapping.getString("app_version");
JSONArray jsonPathArray = mapping.getJSONArray("path");
List<PathComponent> path = new ArrayList<>();
for (int i = 0; i < jsonPathArray.length(); i++) {
  JSONObject jsonPath = jsonPathArray.getJSONObject(i);
  PathComponent component = new PathComponent(jsonPath);
  path.add(component);
String pathType = mapping.optString(Constants.EVENT_MAPPING_PATH_TYPE_KEY,
    Constants.PATH_TYPE_ABSOLUTE);
JSONArray jsonParameterArray = mapping.optJSONArray("parameters");
List<ParameterComponent> parameters = new ArrayList<>();
if (null != jsonParameterArray) {
  for (int i = 0; i < jsonParameterArray.length(); i++) {
    JSONObject jsonParameter = jsonParameterArray.getJSONObject(i);
    ParameterComponent component = new ParameterComponent(jsonParameter);
    parameters.add(component);
String componentId = mapping.optString("component_id");
String activityName = mapping.optString("activity_name");

代码示例来源:origin: facebook/facebook-android-sdk

public static PermissionsPair handlePermissionResponse(JSONObject result)
  throws JSONException {
  JSONObject permissions = result.getJSONObject("permissions");
  JSONArray data = permissions.getJSONArray("data");
  List<String> grantedPermissions = new ArrayList<>(data.length());
  List<String> declinedPermissions = new ArrayList<>(data.length());
  for (int i = 0; i < data.length(); ++i) {
    JSONObject object = data.optJSONObject(i);
    String permission = object.optString("permission");
    if (permission == null || permission.equals("installed")) {
      continue;
    }
    String status = object.optString("status");
    if (status == null) {
      continue;
    }
    if (status.equals("granted")) {
      grantedPermissions.add(permission);
    } else if (status.equals("declined")) {
      declinedPermissions.add(permission);
    }
  }
  return new PermissionsPair(grantedPermissions, declinedPermissions);
}

代码示例来源:origin: org.apache.shindig/shindig-gadgets

@Test
public void parseRssNoSummaries() throws Exception {
 JSONObject feed = processor.process(URL_RSS, DATA_RSS, false, 1);
 feed.getJSONArray("Entry");
 JSONObject entry = feed.getJSONArray("Entry").getJSONObject(0);
 assertNull("Summary should not be returned when getSummaries is false",
   entry.optString("Summary", null));
}

代码示例来源:origin: yanzhenjie/NoHttp

/**
 * From the json format String parsing out the {@code Map<String, List<String>>} data.
 *
 * @param jsonString json string.
 * @throws JSONException thrown it when format error.
 */
public void setJSONString(String jsonString) throws JSONException {
  clear();
  JSONObject jsonObject = new JSONObject(jsonString);
  Iterator<String> keySet = jsonObject.keys();
  while (keySet.hasNext()) {
    String key = keySet.next();
    String value = jsonObject.optString(key);
    JSONArray values = new JSONArray(value);
    for (int i = 0; i < values.length(); i++)
      add(key, values.optString(i));
  }
}

代码示例来源:origin: ankidroid/Anki-Android

private <T> T _dataOnly(JSONObject resp, Class<T> returnType) throws MediaSyncException {
  try {
    if (!TextUtils.isEmpty(resp.optString("err"))) {
      String err = resp.getString("err");
      mCol.log("error returned: " + err);
      return (T) resp.getJSONObject("data");
    } else if (returnType == JSONArray.class) {
      return (T) resp.getJSONArray("data");

代码示例来源:origin: Netflix/EVCache

final JSONObject jsonObj = new JSONObject(js);
final JSONObject application = jsonObj.getJSONObject("application");
final JSONArray instances = application.getJSONArray("instance");
final Map<ServerGroup, EVCacheServerGroupConfig> serverGroupMap = new HashMap<ServerGroup, EVCacheServerGroupConfig>();
final ChainedDynamicProperty.BooleanProperty useBatchPort = EVCacheConfig.getInstance().getChainedBooleanProperty(appName + ".use.batch.port", "evcache.use.batch.port", Boolean.FALSE, null);
for(int i = 0; i < instances.length(); i++) {
  final JSONObject instanceObj = instances.getJSONObject(i);
  final JSONObject metadataObj = instanceObj.getJSONObject("dataCenterInfo").getJSONObject("metadata");
  final String localIp = metadataObj.getString("local-ipv4");
  final JSONObject instanceMetadataObj = instanceObj.getJSONObject("metadata");
  final String evcachePortString = instanceMetadataObj.optString("evcache.port", "11211");
  final String rendPortString = instanceMetadataObj.optString("rend.port", "0");
  final String rendBatchPortString = instanceMetadataObj.optString("rend.batch.port", "0");
  final int rendPort = Integer.parseInt(rendPortString);
  final int rendBatchPort = Integer.parseInt(rendBatchPortString);
  final String rendMemcachedPortString = instanceMetadataObj.optString("rend.memcached.port", "0");
  final String rendMementoPortString = instanceMetadataObj.optString("rend.memento.port", "0");
  final int evcachePort = Integer.parseInt(evcachePortString);
  final int port = rendPort == 0 ? evcachePort : ((useBatchPort.get().booleanValue()) ? rendBatchPort : rendPort);

代码示例来源:origin: jeasonlzy/NineGridView

@Override
  public T parseNetworkResponse(Response response) {
    try {
      String responseData = response.body().string();
      if (TextUtils.isEmpty(responseData)) return null;

      JSONObject jsonObject = new JSONObject(responseData);
      String data = jsonObject.optString("data", "");
      if (clazz == String.class) return (T) data;
      if (clazz != null) return new Gson().fromJson(data, clazz);
      if (type != null) return new Gson().fromJson(data, type);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

代码示例来源:origin: jeremylong/DependencyCheck

final Advisory advisory = new Advisory();
advisory.setId(object.getInt("id"));
advisory.setOverview(object.optString("overview", null));
advisory.setReferences(object.optString("references", null));
advisory.setCreated(object.optString("created", null));
advisory.setUpdated(object.optString("updated", null));
advisory.setRecommendation(object.optString("recommendation", null));
advisory.setTitle(object.optString("title", null));
advisory.setModuleName(object.optString("module_name", null));
advisory.setVulnerableVersions(object.optString("vulnerable_versions", null));
advisory.setPatchedVersions(object.optString("patched_versions", null));
advisory.setAccess(object.optString("access", null));
advisory.setSeverity(object.optString("severity", null));
advisory.setCwe(object.optString("cwe", null));
for (int i = 0; i < findings.length(); i++) {
  final JSONObject finding = findings.getJSONObject(i);
  final String version = finding.optString("version", null);
  final JSONArray paths = finding.optJSONArray("paths");
  for (int j = 0; j < paths.length(); j++) {
    final String path = paths.getString(j);
    if (path != null && path.equals(advisory.getModuleName())) {
final List<String> stringCves = new ArrayList<>();
if (jsonCves != null) {
  for (int j = 0; j < jsonCves.length(); j++) {
    stringCves.add(jsonCves.getString(j));

代码示例来源:origin: facebook/facebook-android-sdk

public static List<String> getCategories(Place place) {
  JSONObject jsonData = place.getJson();
  List<String> categories = new ArrayList<>();
  JSONArray jsonCategories = jsonData.optJSONArray(Place.CATEGORY_LIST);
  if (jsonCategories != null) {
    int length = jsonCategories.length();
    for (int i=0; i<length; i++) {
      JSONObject jsonCategory = jsonCategories.optJSONObject(i);
      if (jsonCategory != null) {
        String category = jsonCategory.optString("name");
        categories.add(category);
      }
    }
  }
  return categories;
}

代码示例来源:origin: parse-community/Parse-SDK-Android

String opString = jsonObject.optString("__op", null);
if (opString != null) {
  try {
String typeString = jsonObject.optString("__type", null);
if (typeString == null) {
  return convertJSONObjectToMap(jsonObject);
  String iso = jsonObject.optString("iso");
  return ParseDateFormat.getInstance().parse(iso);
  String base64 = jsonObject.optString("base64");
  return Base64.decode(base64, Base64.NO_WRAP);
  return decodePointer(jsonObject.optString("className"),
      jsonObject.optString("objectId"));
  List<ParseGeoPoint> coordinates = new ArrayList<>();
  try {
    JSONArray array = jsonObject.getJSONArray("coordinates");
    for (int i = 0; i < array.length(); ++i) {
      JSONArray point = array.getJSONArray(i);
      coordinates.add(new ParseGeoPoint(point.getDouble(0), point.getDouble(1)));

代码示例来源:origin: org.wso2.org.apache.shindig/shindig-gadgets

@Test
public void parseAtomNoSummaries() throws Exception {
 JSONObject feed = processor.process(URL_ATOM, DATA_ATOM, false, 1);
 feed.getJSONArray("Entry");
 JSONObject entry = feed.getJSONArray("Entry").getJSONObject(0);
 assertNull("Summary should not be returned when getSummaries is false",
   entry.optString("Summary", null));
}

代码示例来源:origin: DV8FromTheWorld/JDA

channel = null;
final String groupName = channelObject.optString("name");
final long groupId = channelObject.getLong("id");
final String groupIconId = channelObject.optString("icon", null);
final String guildIconId = guildObject.optString("icon", null);
final long guildId = guildObject.getLong("id");
final String guildName = guildObject.getString("name");
final String guildSplashId = guildObject.optString("splash", null);
final VerificationLevel guildVerificationLevel = VerificationLevel.fromKey(Helpers.optInt(guildObject, "verification_level", -1));
final int presenceCount = Helpers.optInt(object, "approximate_presence_count", -1);
  guildFeatures = Collections.emptySet();
else
  guildFeatures = Collections.unmodifiableSet(StreamSupport.stream(guildObject.getJSONArray("features").spliterator(), false).map(String::valueOf).collect(Collectors.toSet()));

代码示例来源:origin: ankidroid/Anki-Android

/** Update the list of card templates for current note type */
private void updateCards(JSONObject model) {
  Timber.d("updateCards()");
  try {
    JSONArray tmpls = model.getJSONArray("tmpls");
    String cardsList = "";
    // Build comma separated list of card names
    Timber.d("updateCards() template count is %s", tmpls.length());
    for (int i = 0; i < tmpls.length(); i++) {
      String name = tmpls.getJSONObject(i).optString("name");
      // If more than one card then make currently selected card underlined
      if (!mAddNote && tmpls.length() > 1 && model == mEditorNote.model() &&
          mCurrentEditedCard.template().optString("name").equals(name)) {
        name = "<u>" + name + "</u>";
      }
      cardsList += name;
      if (i < tmpls.length()-1) {
        cardsList += ", ";
      }
    }
    // Make cards list red if the number of cards is being reduced
    if (!mAddNote && tmpls.length() < mEditorNote.model().getJSONArray("tmpls").length()) {
      cardsList = "<font color='red'>" + cardsList + "</font>";
    }
    mCardsButton.setText(CompatHelper.getCompat().fromHtml(getResources().getString(R.string.CardEditorCards, cardsList)));
  } catch (JSONException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: stackoverflow.com

// Note the null is the continueToken you may not get all of the purchased items
// in one call - check ownedItems.getString("INAPP_CONTINUATION_TOKEN") for 
// the next continueToken and re-call with that until you don't get a token
Bundle ownedItems = service.getPurchases(3, getPackageName(), "inapp", null);
// Check response
int responseCode = ownedItems.getInt("RESPONSE_CODE");
if (responseCode != 0) {
  throw new Exception("Error");
}
// Get the list of purchased items
ArrayList<String> purchaseDataList = 
  ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
for (String purchaseData : purchaseDataList) {
  JSONObject o = new JSONObject(purchaseData);
  String purchaseToken = o.optString("token", o.optString("purchaseToken"));
  // Consume purchaseToken, handling any errors
  mService.consumePurchase(3, getPackageName(), purchaseToken);
}

代码示例来源:origin: facebook/facebook-android-sdk

JSONObject jsonResponse = response.getJSONObject();
assertNotNull(jsonResponse);
String albumId = jsonResponse.optString("id");
assertNotNull(albumId);
for (int i = 0; i < jsonList.length(); i++) {
  JSONObject imageObject = jsonList.getJSONObject(i);
  if (imageId.get().equals(imageObject.optString("id"))) {
    found = true;

代码示例来源:origin: facebook/facebook-android-sdk

for (int i = 0; i < permissionsArray.length(); i++) {
  JSONObject permissionEntry = permissionsArray.optJSONObject(i);
  if (permissionEntry == null) {
    continue;
  String permission = permissionEntry.optString("permission");
  String status = permissionEntry.optString("status");
  if (!Utility.isNullOrEmpty(permission) &&
      !Utility.isNullOrEmpty(status)) {

代码示例来源:origin: DV8FromTheWorld/JDA

public EmoteImpl createEmote(GuildImpl guildObj, JSONObject json, boolean fake)
{
  JSONArray emoteRoles = json.isNull("roles") ? new JSONArray() : json.getJSONArray("roles");
  final long emoteId = json.getLong("id");
  final User user = json.isNull("user") ? null : createFakeUser(json.getJSONObject("user"), false);
  EmoteImpl emoteObj = (EmoteImpl) guildObj.getEmoteById(emoteId);
  if (emoteObj == null)
    emoteObj = new EmoteImpl(emoteId, guildObj, fake);
  Set<Role> roleSet = emoteObj.getRoleSet();
  roleSet.clear();
  for (int j = 0; j < emoteRoles.length(); j++)
  {
    Role role = guildObj.getRoleById(emoteRoles.getString(j));
    if (role != null)
      roleSet.add(role);
  }
  if (user != null)
    emoteObj.setUser(user);
  return emoteObj
      .setName(json.optString("name"))
      .setAnimated(json.optBoolean("animated"))
      .setManaged(Helpers.optBoolean(json, "managed"));
}

相关文章

JSONObject类方法