com.atlassian.jira.util.json.JSONObject类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(15.4k)|赞(0)|评价(0)|浏览(183)

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

JSONObject介绍

[英]A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods. A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

The generic get() and opt() methods return an object, which you can cast or query for type. There are also typed get and opt methods that do type checking and type coersion for you.

The put methods adds values to an object. For example,

myString = new JSONObject().put("JSON", "Hello, World!").toString();

produces the string {"JSON": "Hello, World"}.

The texts produced by the toString methods strictly conform to the JSON sysntax rules. The constructors are more forgiving in the texts they will accept:

  • An extra , (comma) may appear just before the closing brace.
  • Strings may be quoted with ' (single quote).
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.
  • Keys can be followed by = or => as well as by :.
  • Values can be followed by ; (semicolon) as well as by , (comma).
  • Numbers may have the 0- (octal) or 0x- (hex) prefix.
  • Comments written in the slashshlash, slashstar, and hash conventions will be ignored.
    [中]JSONObject是名称/值对的无序集合。它的外部形式是一个用大括号括起来的字符串,名称和值之间用冒号,值和名称之间用逗号。内部表单是一个对象,它具有getopt方法用于按名称访问值,以及put方法用于按名称添加或替换值。这些值可以是以下类型中的任意一种:BooleanJSONArrayJSONObjectNumberStringJSONObject.NULL对象。JSONObject构造函数可用于将外部表单JSON文本转换为内部表单,其值可通过getopt方法检索,或使用puttoString方法将值转换为JSON文本。如果可以找到get方法,则返回一个值;如果找不到,则抛出一个异常。opt方法返回默认值而不是引发异常,因此对于获取可选值非常有用。
    泛型get()opt()方法返回一个对象,您可以强制转换或查询该对象的类型。还有类型化的getopt方法可以为您进行类型检查和类型协同。
    put方法向对象添加值。例如
myString = new JSONObject().put("JSON", "Hello, World!").toString();

生成字符串{"JSON": "Hello, World"}
toString方法生成的文本严格遵守JSON sysntax规则。构造器在他们将接受的文本中更加宽容:
*右大括号前可能会出现额外的,(逗号)。
*字符串可以用'引用(单引号)。
*如果字符串不以引号或单引号开头,如果字符串不包含前导空格或尾随空格,如果字符串不包含这些字符中的任何字符:[24$]],如果字符串看起来不像数字,如果字符串不是保留字truefalsenull,则根本不需要使用引号。
*键后面可以跟==>以及:
*值后面可以跟;(分号)和,(逗号)。
*数字可以有0-(八进制)或0x-(十六进制)前缀。
*以slashshlash、slashstar和哈希约定编写的注释将被忽略。

代码示例

代码示例来源:origin: com.atlassian.plugin.automation/jira-automation-spi

public String getJSONString()
{
  try
  {
    return new JSONObject().put(LAST_KEY, last).put(ALL_KEY, all).toString();
  }
  catch (JSONException e)
  {
    return "{}";
  }
}

代码示例来源:origin: com.atlassian.plugin.deflection/deflection-hot-issues

protected List<SearchResult> searchJQL(int filterID, String filterName) throws IOException, JSONException
{
  List<SearchResult> results = Lists.newArrayList();
  JSONArray issueList = new JSONObject(searchResults(filterID)).getJSONArray("issues");
  for (int i = 0; i < issueList.length(); i++)
  {
    JSONObject issue = issueList.getJSONObject(i);
    String title = issue.getString("key");
    String content = issue.getJSONObject("fields").getString("summary");
    String url = JAC_BASE_URL + "/browse/" + issue.getString("key");
    String source = "HotIssues" + filterName;
    results.add(new DefaultSearchResult(content, url, title, source, ""));
  }
  return results;
}

代码示例来源:origin: com.atlassian.jira/jira-api

/**
 * Get an optional int value associated with a key,
 * or the default if there is no such key or if the value is not a number.
 * If the value is a string, an attempt will be made to evaluate it as
 * a number.
 *
 * @param key          A key string.
 * @param defaultValue The default.
 * @return An object which is the value.
 */
public int optInt(final String key, final int defaultValue)
{
  try
  {
    return getInt(key);
  }
  catch (final Exception e)
  {
    return defaultValue;
  }
}

代码示例来源:origin: com.atlassian.jira/jira-api

/**
 * Put a key/value pair in the JSONObject, where the value will be a
 * JSONObject which is produced from a Map.
 *
 * @param key   A key string.
 * @param value A Map value.
 * @return this.
 * @throws JSONException If the value is non-finite number or if the key is null.
 */
public JSONObject put(final String key, final Map<String, Object> value) throws JSONException
{
  put(key, new JSONObject(value));
  return this;
}

代码示例来源:origin: com.marvelution.jira.plugins/jira-jenkins-plugin

/**
 * Helper method to get the optional {@link String} element of the given {@link JSONObject} given by the key given
 *
 * @param json the {@link JSONObject} to get the {@link String} value from
 * @param key  the key to get he corresponding value of
 * @return the {@link String} value, maybe {@code null}
 */
private String optJsonString(JSONObject json, String key) {
  if (json.has(key) && !json.isNull(key)) {
    return json.optString(key);
  } else {
    return null;
  }
}

代码示例来源:origin: com.atlassian.jira/jira-issue-link-remote-jira-plugin

final JSONObject json = new JSONObject(new JSONTokener(responseString));
final JSONObject fields = json.getJSONObject("fields");
    builder.id(json.getLong("id"));
    builder.summary(fields.getString("summary"));
    final String key = json.getString("key");
    builder.key(key);
    builder.browseUrl(buildIssueUrl(baseUri, key));
    final JSONObject issueType = fields.getJSONObject("issuetype");
    builder.iconUrl(issueType.getString("iconUrl"));
    builder.iconTitle(appendNameAndDescription(issueType));
    final JSONObject status = fields.getJSONObject("status");
    builder.statusIconUrl(status.getString("iconUrl"));
    builder.statusName(status.getString("name"));
    builder.statusDescription(status.optString("description"));
    builder.statusIconTitle(appendNameAndDescription(status));
    if (status.has("statusCategory"))
      final JSONObject statusCategory = status.getJSONObject("statusCategory");
      builder.statusCategoryKey(statusCategory.getString("key"));
      builder.statusCategoryColorName(statusCategory.getString("colorName"));
    builder.resolved(!fields.isNull("resolution"));
    break;

代码示例来源:origin: com.atlassian.jira/jira-core

private JSONObject getObject()
{
  if (delegateSupplier.get().isAdminWithoutIssuePermission())
  {
    return new JSONObject(DATA);
  }
  else
  {
    return new JSONObject();
  }
}

代码示例来源:origin: com.atlassian.cpji/cpji-jira-plugin

private static ErrorCollection convertJsonToErrorCollection(final JSONObject json)
{
  final ErrorCollection errors = new SimpleErrorCollection();
  try
  {
    final JSONArray errorMessages = json.getJSONArray("errorMessages");
    for (int i = 0; i < errorMessages.length(); i++)
    {
      errors.addErrorMessage(errorMessages.getString(i));
    }
    final JSONObject errorsMap = json.getJSONObject("errors");
    final Iterator<String> keys = errorsMap.keys();
    while (keys.hasNext())
    {
      final String key = keys.next();
      errors.addError(key, errorsMap.getString(key));
    }
  }
  catch (final JSONException e)
  {
    return null;
  }
  return errors;
}

代码示例来源:origin: com.atlassian.plugin.deflection/deflection-outages

protected List<SearchResult> searchApplicationsInstanceStatus(String instanceURL) throws IOException, JSONException
{
  List<SearchResult> results = Lists.newArrayList();
  String searchURL = java.lang.String.format("%s/status_rest/get_instance_stats/%s?key=%s&verify=false", HOPS_STATUS_URL, instanceURL, HOPS_STATUS_API_KEY);
  JSONObject applicationParamStatusObj = new JSONObject(getJSON(searchURL));
  Iterator<String> allKeys = applicationParamStatusObj.keys();
  while (allKeys.hasNext())
  {
    String applicationKey = allKeys.next().toString();
    JSONObject applicationParam = applicationParamStatusObj.getJSONObject(applicationKey);
    String status = applicationParam.getString("status");
    String source = applicationParam.getString("scheduled");
    results.add(new DefaultSearchResult(status, instanceURL, applicationKey, source));
  }
  return results;
}

代码示例来源:origin: com.atlassian.jirawallboard/atlassian-wallboard-plugin

static public WallboardPluginSettings loadSettings(PluginSettingsFactory pluginSettingsFactory, ApplicationUser user)
{
  WallboardPluginSettings settings = new WallboardPluginSettings(pluginSettingsFactory, user);
  Object val = pluginSettingsFactory.createGlobalSettings().get(WALLBOARD_KEY + mapNullToBlank(settings.userKey));
  if (val == null)
  {
    settings.isConfigured = false;
    return settings;
  }
  JSONObject jsonRepresentation;
  try
  {
    jsonRepresentation = new JSONObject((String) val);
    JSONArray rawDashboardIds = jsonRepresentation.getJSONArray("dashboardIds");
    settings.dashboardIds = new ArrayList<>(rawDashboardIds.length());
    for (int i = 0; i < rawDashboardIds.length(); i++)
    {
      settings.dashboardIds.add(i, (String) rawDashboardIds.get(i));
    }
    settings.setCyclePeriod(jsonRepresentation.getInt(WallboardServlet.CYCLE_PERIOD.getKey()));
    settings.setTransitionFx(jsonRepresentation.getString(WallboardServlet.TRANSITION_FX.getKey()));
    settings.setRandom(jsonRepresentation.getBoolean(WallboardServlet.RANDOM.getKey()));
  }
  catch (JSONException e)
  {
    settings.isConfigured = false;
  }
  return settings;
}

代码示例来源:origin: com.marvelution.jira.plugins/jira-jenkins-plugin

build.setTimestamp(jsonBuild.getLong("timestamp"));
build.setDuration(jsonBuild.getLong("duration"));
final JSONArray actions = jsonBuild.optJSONArray("actions");
if (actions != null) {
  for (int index = 0; index < actions.length(); index++) {
    if (object.has("causes")) {
      JSONArray causes = object.optJSONArray("causes");
      for (int ii = 0; ii < causes.length(); ii++) {
        final JSONObject cause = causes.getJSONObject(ii);
        if (cause.has("shortDescription")) {
          build.setCause(cause.getString("shortDescription"));
          break;
    } else if (object.has("urlName") && "testReport".equals(object.getString("urlName"))) {
      build.setTestResults(new TestResults(object.getInt("failCount"), object.getInt("skipCount"),
                         object.getInt("totalCount")));
final JSONArray artifacts = jsonBuild.optJSONArray("artifacts");
if (artifacts != null && artifacts.length() > 0) {
  for (int index = 0; index < artifacts.length(); index++) {
    final JSONObject artifact = artifacts.getJSONObject(index);
    build.getArtifacts().add(new Artifact(artifact.getString("fileName"),
                       artifact.getString("displayPath"), artifact.getString("relativePath")));
final JSONArray culprits = jsonBuild.optJSONArray("culprits");
if (culprits != null && culprits.length() > 0) {

代码示例来源:origin: com.atlassian.plugin.deflection/deflection-cse

searchResult = new JSONObject(performSearch(searchQuery,
    startIndex,
    properties.getString(CseProperties.GSE_CONTEXT),
    RESULTS_PER_QUERY));
JSONArray jsonResults = searchResult.getJSONArray("results");
      final DefaultSearchResult cseSearchResult = new DefaultSearchResult(result.getString(RESULT_CONTENT),
          result.getString(RESULT_URL),
          result.getString(RESULT_TITLE),
          MODULE_NAME,
          getEmbedURL(result));

代码示例来源:origin: com.atlassian.plugin.deflection/deflection-outages

protected String getPluginStatusKey() throws IOException, JSONException
{
  //Will get the plugin status either ENABLE or DISABLE
  JSONObject applicationParamStatusObj = new JSONObject(getJSON(PLUGIN_STATUS_KEY_URL));
  return applicationParamStatusObj.getString("status");
}

代码示例来源:origin: com.atlassian.plugin.deflection/deflection-cse

public static boolean resultMatches(JSONObject result, Iterable<String> patternToMatch) throws JSONException
  {
    if (result.has("richSnippet"))
    {
      final JSONObject richSnippet = result.getJSONObject("richSnippet");
      if (richSnippet.has("metatags"))
      {
        final JSONObject metatags = richSnippet.getJSONObject("metatags");
        if (metatags.has("confluenceSpaceKey"))
        {
          final String spaceKey = metatags.getString("confluenceSpaceKey");
          for (String pattern : patternToMatch)
          {
            if (spaceKey.matches(pattern))
            {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
}

代码示例来源:origin: com.atlassian.jira/jira-api

return numberToString((Number) value);
  return ((JSONObject) value).toString(indentFactor, indent);
  final JSONObject result = new JSONObject(Map.class.cast(value));
  return result.toString(indentFactor, indent);
return quote(value.toString());

代码示例来源:origin: com.atlassian.jira/jira-api

@Nonnull
public static RemoteProject from(ApplicationLink applicationLink, final JSONObject jsonObject) throws JSONException
{
  Builder builder = new Builder();
  builder.applicationLink(applicationLink);
  builder.id(jsonObject.getLong("id"));
  builder.key(jsonObject.getString("key"));
  builder.name(jsonObject.getString("name"));
  if (jsonObject.has("description"))
    builder.description(jsonObject.getString("description"));
  if (jsonObject.has("url"))
    builder.url(jsonObject.getString("url"));
  if (jsonObject.has("lead"))
    builder.leadUser(RemoteUser.from(jsonObject.getJSONObject("lead")));
  if (jsonObject.has("avatarUrls"))
    builder.avatar(RemoteAvatar.from(jsonObject.getJSONObject("avatarUrls")));
  return builder.build();
}

代码示例来源:origin: com.atlassian.jira/jira-api

@Override
  public EntityPropertyBean apply(final Map<String, Object> entityPropertyBean)
  {
    final String key = (String) entityPropertyBean.get("key");
    final Map<String, Object> value = (Map<String, Object>) entityPropertyBean.get("value");
    return new EntityPropertyBean(key, new JSONObject(value).toString(), null);
  }
}));

代码示例来源:origin: com.marvelution.jira.plugins/jira-jenkins-plugin

@Override
public List<Job> getJobs() {
  List<Job> jobs = Lists.newArrayList();
  try {
    RestResponse response = executeGetRequest("/api/json", CALL_TIMEOUT);
    if (response.getJson() != null && response.getJson().has("jobs")) {
      JSONArray json = response.getJson().getJSONArray("jobs");
      LOGGER.info("Found {} jobs", new Object[] { json.length() });
      for (int index = 0; index < json.length(); index++) {
        final JSONObject jsonJob = json.getJSONObject(index);
        jobs.add(new Job(site.getId(), jsonJob.getString("name")));
      }
    } else {
      handleNoJsonResponse(response);
    }
  } catch (CredentialsRequiredException e) {
    LOGGER.error("Authentication failure on {} [{}]: {}", new Object[] { applicationLink.getName(),
                                       applicationLink.getDisplayUrl(), e.getMessage() });
  } catch (JSONException e) {
    LOGGER.error("Failed to get the Job list from {}: {}", applicationLink.getName(), e.getMessage());
  }
  return jobs;
}

代码示例来源:origin: com.atlassian.jira/jira-api

/**
 * Put a key/boolean pair in the JSONObject.
 *
 * @param key   A key string.
 * @param value A boolean which is the value.
 * @return this.
 * @throws JSONException If the key is null.
 */
public JSONObject put(final String key, final boolean value) throws JSONException
{
  put(key, value ? Boolean.TRUE : Boolean.FALSE);
  return this;
}

代码示例来源:origin: com.marvelution.jira.plugins/jira-jenkins-plugin

job.setDisplayName(optJsonString(json, "displayName"));
job.setDescription(optJsonString(json, "description"));
job.setBuildable(json.optBoolean("buildable", true));
job.setInQueue(json.optBoolean("inQueue"));
final JSONObject firstBuild = json.optJSONObject("firstBuild");
if (firstBuild != null && firstBuild.has("number")) {
  job.setOldestBuild(firstBuild.optInt("number", -1));
final JSONArray builds = json.optJSONArray("builds");
if (builds != null && builds.length() > 0) {
  for (int index = 0; index < builds.length(); index++) {
    final JSONObject jsonBuild = builds.getJSONObject(index);
    final Build build = new Build(job.getId(), jsonBuild.getInt("number"));
    job.getBuilds().add(build);

相关文章