org.codehaus.jettison.json.JSONObject类的使用及代码示例

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

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

@GET
@Path("/status")
@Produces(MediaType.APPLICATION_JSON)
public Response status() throws Exception {
  JSONObject object = new JSONObject();
  object.put("SnapshotStatus", snapshotBackup.state().toString());
  return Response.ok(object.toString(), MediaType.APPLICATION_JSON).build();
}

代码示例来源:origin: apache/nifi

JSONObject jobInfo = readJSONObjectFromUrlPOST(statementUrl, livySessionService, headers, payload);
log.debug("submitAndHandleJob() Job Info: " + jobInfo);
String statementId = String.valueOf(jobInfo.getInt("id"));
statementUrl = statementUrl + "/" + statementId;
jobInfo = readJSONObjectFromUrl(statementUrl, livySessionService, headers);
String jobState = jobInfo.getString("state");
if (jobState.equalsIgnoreCase("available")) {
  log.debug("submitAndHandleJob() Job status is: " + jobState + ". returning output...");
  output = jobInfo.getJSONObject("output");
} else if (jobState.equalsIgnoreCase("running") || jobState.equalsIgnoreCase("waiting")) {
  while (!jobState.equalsIgnoreCase("available")) {
    Thread.sleep(statusCheckInterval);
    jobInfo = readJSONObjectFromUrl(statementUrl, livySessionService, headers);
    jobState = jobInfo.getString("state");
  output = jobInfo.getJSONObject("output");
} else if (jobState.equalsIgnoreCase("error")
    || jobState.equalsIgnoreCase("cancelled")

代码示例来源:origin: json-path/JsonPath

@Override
public Object next() 
{
  try
  {
    return jettisonUnwrap(jsonObject.get(String.valueOf(jsonKeysIt.next())));
  }
  catch( org.codehaus.jettison.json.JSONException jsonException )
  {
    throw new NoSuchElementException(jsonException.toString());
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected JSONArray addContactData(final HttpServletRequest request) throws JSONException {
  final JSONArray contactList = new JSONArray();
  final JSONObject contact = new JSONObject();
  
  contact.put("@type", "ContactPoint");
  contact.put("telephone", getSiteCustomerServiceNumber());
  contact.put("contactType", "customerService");
  extensionManager.getProxy().addContactData(request, contact);
  
  contactList.put(contact);
  
  return contactList;
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected JSONObject addPotentialActions(final HttpServletRequest request) throws JSONException {
  final JSONObject potentialAction = new JSONObject();
  potentialAction.put("@type", "SearchAction");
  potentialAction.put("target", getSiteBaseUrl() + getSiteSearchUri());
  potentialAction.put("query-input", "required name=query");
  extensionManager.getProxy().addPotentialActionsData(request, potentialAction);
  return potentialAction;
}

代码示例来源:origin: org.apache.apex/apex-engine

@GET
@Path(PATH_PHYSICAL_PLAN)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getPhysicalPlan() throws Exception
{
 init();
 Map<String, Object> result = new HashMap<>();
 result.put("operators", dagManager.getOperatorInfoList());
 result.put("streams", dagManager.getStreamInfoList());
 return new JSONObject(objectMapper.writeValueAsString(result));
}

代码示例来源:origin: org.apache.apex/apex-engine

@POST
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId:\\d+}/ports/{portName}/" + PATH_RECORDINGS_STOP)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject stopRecording(@PathParam("opId") int opId, @PathParam("portName") String portName)
{
 init();
 LOG.debug("Stop recording on {}.{} requested", opId, portName);
 JSONObject response = new JSONObject();
 dagManager.stopRecording(opId, portName);
 return response;
}

代码示例来源:origin: org.apache.apex/apex-engine

@POST // not supported by WebAppProxyServlet, can only be called directly
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId:\\d+}/properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject setPhysicalOperatorProperties(JSONObject request, @PathParam("operatorId") int operatorId)
{
 init();
 JSONObject response = new JSONObject();
 try {
  @SuppressWarnings("unchecked")
  Iterator<String> keys = request.keys();
  while (keys.hasNext()) {
   String key = keys.next();
   String val = request.isNull(key) ? null : request.getString(key);
   dagManager.setPhysicalOperatorProperty(operatorId, key, val);
  }
 } catch (JSONException ex) {
  LOG.warn("Got JSON Exception: ", ex);
 }
 return response;
}

代码示例来源:origin: org.apache.apex/apex-engine

@POST
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId:\\d+}/" + PATH_RECORDINGS_START)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject startRecording(@PathParam("opId") int opId, String content) throws JSONException
{
 init();
 LOG.debug("Start recording on {} requested", opId);
 JSONObject response = new JSONObject();
 long numWindows = 0;
 if (StringUtils.isNotBlank(content)) {
  JSONObject r = new JSONObject(content);
  numWindows = r.optLong("numWindows", 0);
 }
 String id = getTupleRecordingId();
 dagManager.startRecording(id, opId, null, numWindows);
 response.put("id", id);
 return response;
}

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

return Response.status(503).entity("JMXConnectionException").build();
JSONObject rootObj = new JSONObject();
CompactionManagerMBean cm = nodeTool.getCompactionManagerProxy();
rootObj.put("pending tasks", cm.getPendingTasks());
JSONArray compStats = new JSONArray();
for (Map<String, String> c : cm.getCompactions()) {
  JSONObject cObj = new JSONObject();
  cObj.put("id", c.get("id"));
  cObj.put("keyspace", c.get("keyspace"));
  cObj.put("columnfamily", c.get("columnfamily"));
  cObj.put("bytesComplete", c.get("bytesComplete"));
  cObj.put("totalBytes", c.get("totalBytes"));
  cObj.put("taskType", c.get("taskType"));
  String percentComplete =
      new Long(c.get("totalBytes")) == 0
                          * 100)
              + "%";
  cObj.put("progress", percentComplete);
  compStats.put(cObj);
rootObj.put("compaction stats", compStats);
return Response.ok(rootObj, MediaType.APPLICATION_JSON).build();

代码示例来源:origin: opensourceBIM/BIMserver

@Override
public List<SModelCheckerInstance> getAllRepositoryModelCheckers() throws ServerException, UserException {
  requireRealUserAuthentication();
  try {
    List<SModelCheckerInstance> modelCheckers = new ArrayList<SModelCheckerInstance>();
    String content = NetUtils.getContent(new URL(getServiceMap().get(SettingsInterface.class).getServiceRepositoryUrl() + "/modelcheckers"), 5000);
    JSONObject root = new JSONObject(new JSONTokener(content));
    JSONArray modelCheckersJson = root.getJSONArray("modelcheckers");
    for (int i = 0; i < modelCheckersJson.length(); i++) {
      JSONObject modelCheckerJson = modelCheckersJson.getJSONObject(i);
      
      SModelCheckerInstance sModelChecker = new SModelCheckerInstance();
      sModelChecker.setName(modelCheckerJson.getString("name"));
      sModelChecker.setCode(modelCheckerJson.getString("code"));
      sModelChecker.setDescription(modelCheckerJson.getString("description"));
      sModelChecker.setModelCheckerPluginClassName(modelCheckerJson.getString("modelCheckerPluginClassName"));
    
      modelCheckers.add(sModelChecker);
    }
    return modelCheckers;
  } catch (Exception e) {
    return handleException(e);
  }
}

代码示例来源:origin: opensourceBIM/BIMserver

URL url = new URL(getServiceMap().get(SettingsInterface.class).getServiceRepositoryUrl() + "/services.json");
String content = NetUtils.getContent(url, 5000);
JSONObject root = new JSONObject(new JSONTokener(content));
JSONArray services = root.getJSONArray("services");
for (int i = 0; i < services.length(); i++) {
  JSONObject service = services.getJSONObject(i);
  SServiceDescriptor sServiceDescriptor = new SServiceDescriptor();
  sServiceDescriptor.setName(service.getString("name"));
  sServiceDescriptor.setIdentifier(service.getString("identifier"));
  sServiceDescriptor.setDescription(service.getString("description"));
  sServiceDescriptor.setNotificationProtocol(SAccessMethod.valueOf(service.getString("notificationProtocol")));
  sServiceDescriptor.setTrigger(STrigger.valueOf(service.getString("trigger")));
  sServiceDescriptor.setUrl(service.getString("url"));
  sServiceDescriptor.setCompanyUrl(service.getString("companyUrl"));
  sServiceDescriptor.setTokenUrl(service.getString("tokenUrl"));
  sServiceDescriptor.setNewProfileUrl(service.getString("newProfileUrl"));
  sServiceDescriptor.setProviderName(service.getString("providerName"));
  sServiceDescriptor.setRegisterUrl(service.getString("registerUrl"));
  sServiceDescriptor.setAuthorizeUrl(service.getString("authorizeUrl"));
  JSONObject rights = service.getJSONObject("rights");
  sServiceDescriptor.setReadRevision(rights.has("readRevision") && rights.getBoolean("readRevision"));
  sServiceDescriptor.setReadExtendedData(rights.has("readExtendedData") ? rights.getString("readExtendedData") : null);
  sServiceDescriptor.setWriteRevision(rights.has("writeRevision") && rights.getBoolean("writeRevision"));
  sServiceDescriptor.setWriteExtendedData(rights.has("writeExtendedData") ? rights.getString("writeExtendedData") : null);
  sServiceDescriptors.add(sServiceDescriptor);

代码示例来源:origin: org.apache.hadoop/hadoop-yarn-server-resourcemanager

private JSONObject getSubQueue(JSONObject queue, String subQueue)
 throws JSONException {
 JSONArray queues = queue.getJSONObject("queues").getJSONArray("queue");
 for (int i=0; i<queues.length(); ++i) {
  checkResourcesUsed(queues.getJSONObject(i));
  if (queues.getJSONObject(i).getString("queueName").equals(subQueue) ) {
   return queues.getJSONObject(i);
  }
 }
 return null;
}

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

private String getFieldStringValue(final JSONObject json, final String attributeName) throws JSONException {
  final JSONObject fieldsJson = json.getJSONObject(FIELDS);
  final Object summaryObject = fieldsJson.get(attributeName);
  if (summaryObject instanceof JSONObject) { // pre JIRA 5.0 way
    return ((JSONObject) summaryObject).getString(VALUE_ATTR);
  }
  if (summaryObject instanceof String) { // JIRA 5.0 way
    return (String) summaryObject;
  }
  throw new JSONException("Cannot parse [" + attributeName + "] from available fields");
}

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

private void notify(AbstractBackupPath abp, String uploadStatus) {
  JSONObject jsonObject = new JSONObject();
  try {
    jsonObject.put("s3bucketname", this.config.getBackupPrefix());
    jsonObject.put("s3clustername", abp.getClusterName());
    jsonObject.put("s3namespace", abp.getRemotePath());
    jsonObject.put("keyspace", abp.getKeyspace());
    jsonObject.put("cf", abp.getColumnFamily());
    jsonObject.put("region", abp.getRegion());
    jsonObject.put("rack", instanceInfo.getRac());
    jsonObject.put("token", abp.getToken());
    jsonObject.put("filename", abp.getFileName());
    jsonObject.put("uncompressfilesize", abp.getSize());
    jsonObject.put("compressfilesize", abp.getCompressedFileSize());
    jsonObject.put("backuptype", abp.getType().name());
    jsonObject.put("uploadstatus", uploadStatus);
    jsonObject.put("compression", abp.getCompression().name());
    jsonObject.put("encryption", abp.getEncryption().name());
            .withStringValue(abp.getType().name()));
    this.notificationService.notify(jsonObject.toString(), messageAttributes);
  } catch (JSONException exception) {
    logger.error(
        uploadStatus,
        abp.getFileName(),
        exception.getLocalizedMessage());

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
protected JSONArray getLinkedDataJsonInternal(final String url, final HttpServletRequest request,
                       final JSONArray schemaObjects) throws JSONException {
  final JSONObject categoryData = new JSONObject();
  
  categoryData.put("@context", getStructuredDataContext());
  categoryData.put("@type", "ItemList");
  addCategoryProductData(request, categoryData);
  
  extensionManager.getProxy().addCategoryData(request, categoryData);
  schemaObjects.put(categoryData);
  return schemaObjects;
}

代码示例来源:origin: org.apache.hadoop/hadoop-mapreduce-client-app

public void verifyJobAttempts(JSONObject info, Job job)
  throws JSONException {
 JSONArray attempts = info.getJSONArray("jobAttempt");
 assertEquals("incorrect number of elements", 2, attempts.length());
 for (int i = 0; i < attempts.length(); i++) {
  JSONObject attempt = attempts.getJSONObject(i);
  verifyJobAttemptsGeneric(job, attempt.getString("nodeHttpAddress"),
    attempt.getString("nodeId"), attempt.getInt("id"),
    attempt.getLong("startTime"), attempt.getString("containerId"),
    attempt.getString("logsLink"));
 }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

fieldDTO.setValues(new JSONObject(enumMap).toString());
} else if (field.getFieldType().equals("ADDITIONAL_FOREIGN_KEY")) {
  fieldDTO.setOperators("blcFilterOperators_Selectize");

代码示例来源:origin: KylinOLAP/Kylin

public String getKylinProperties() throws IOException {
  String url = baseUrl + "/admin/config";
  HttpMethod request = new GetMethod(url);
  try {
    int code = client.executeMethod(request);
    String msg = Bytes.toString(request.getResponseBody());
    JSONObject obj = new JSONObject(msg);
    msg = obj.getString("config");
    if (code != 200)
      throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg);
    return msg;
  } catch (JSONException e) {
    throw new IOException("Error when parsing json response from REST");
  } finally {
    request.releaseConnection();
  }
}

代码示例来源:origin: eBay/parallec

hasMoreNextUrl = null;
if (jsonObjectNext.has(KEY_HAS_MORE)) {
  hasMore = jsonObjectNext.getBoolean(KEY_HAS_MORE);
  if (jsonObjectNext.has(KEY_NEXT_PARENT)
      && jsonObjectNext.getJSONObject(KEY_NEXT_PARENT)
          .has(KEY_NEXT_URL)) {
    hasMoreNextUrl = jsonObjectNext.getJSONObject(
        KEY_NEXT_PARENT).getString(KEY_NEXT_URL);

相关文章