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

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

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

JSONException介绍

[英]The JSONException is thrown by the JSON.org classes then things are amiss.
[中]JSONException由JSON抛出。那么事情就不对劲了。

代码示例

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

JSONArray jArray = new JSONArray();
  while (it.hasNext()) {
    AbstractBackupPath p = it.next();
    if (!filter.isEmpty() && BackupFileType.valueOf(filter) != p.getType()) continue;
    JSONObject backupJSON = new JSONObject();
    backupJSON.put("bucket", config.getBackupPrefix());
    backupJSON.put("filename", p.getRemotePath());
    backupJSON.put("app", p.getClusterName());
    backupJSON.put("region", p.getRegion());
        jArray.put(backupJSON);
        backupJSON.put("num_files", "1");
      jArray.put(backupJSON);
  object.put("num_files", fileCnt);
} catch (JSONException jse) {
  logger.info("Caught JSON Exception --> {}", jse.getMessage());

代码示例来源:origin: org.codehaus.jettison/jettison

/**
 * Append values to the array under a key. If the key does not exist in the
 * JSONObject, then the key is put in the JSONObject with its value being a
 * JSONArray containing the value parameter. If the key was already
 * associated with a JSONArray, then the value parameter is appended to it.
 * @param key   A key string.
 * @param value An object to be accumulated under the key.
 * @return this.
 * @throws JSONException If the key is null or if the current value 
 *  associated with the key is not a JSONArray.
 */
public JSONObject append(String key, Object value)
    throws JSONException {
  testValidity(value);
  Object o = opt(key);
  if (o == null) {
    put(key, new JSONArray().put(value));
  } else if (!(o instanceof JSONArray)){
    throw new JSONException("JSONObject[" + key + 
          "] is not a JSONArray.");
  } else {
    ((JSONArray)o).put(value);
  }
  return this;
}

代码示例来源: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());
        uploadStatus,
        abp.getFileName(),
        exception.getLocalizedMessage());

代码示例来源:origin: org.codehaus.jettison/jettison

public XMLStreamReader createXMLStreamReader(JSONTokener tokener) throws XMLStreamException {
  try {
    JSONObject root = createJSONObject(tokener);
    return new MappedXMLStreamReader(root, convention);
  } catch (JSONException e) {
    int column = e.getColumn();
    if (column == -1) {
      throw new XMLStreamException(e);
    } else {
      throw new XMLStreamException(e.getMessage(),
                     new ErrorLocation(e.getLine(), e.getColumn()),
                     e);
    }
  }
}

代码示例来源:origin: org.gradoop/gradoop-flink

/**
  * Creates a JSON string representation of a given graph head object.
  *
  * @param g graph head
  * @return JSON string representation
  */
 @Override
 public String format(G g) {
  JSONObject json = new JSONObject();
  try {
   json.put(JSONConstants.IDENTIFIER, g.getId());
   json.put(JSONConstants.DATA, writeProperties(g));
   json.put(JSONConstants.META, writeGraphMeta(g));
  } catch (JSONException ex) {
   ex.printStackTrace();
  }
  return json.toString();
 }
}

代码示例来源:origin: GluuFederation/oxAuth

@Parameters({"endSessionPath"})
@Test(enabled = true) // switched off test : WebApplicationException seems to not translated correctly into response by container and results in 500 error. See org.xdi.oxauth.session.ws.rs.EndSessionRestWebServiceImpl.endSession()
public void requestEndSessionFail1(final String endSessionPath) throws Exception {
  EndSessionRequest endSessionRequest = new EndSessionRequest(null, null, null);
  Builder request = ResteasyClientBuilder.newClient()
      .target(url.toString() + endSessionPath + "?" + endSessionRequest.getQueryString()).request();
  request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
  Response response = request.get();
  String entity = response.readEntity(String.class);
  showResponse("requestEndSessionFail1", response, entity);
  assertEquals(response.getStatus(), 400, "Unexpected response code.");
  assertNotNull(entity, "Unexpected result: " + entity);
  try {
    JSONObject jsonObj = new JSONObject(entity);
    assertTrue(jsonObj.has("error"), "The error type is null");
    assertTrue(jsonObj.has("error_description"), "The error description is null");
  } catch (JSONException e) {
    e.printStackTrace();
    fail(e.getMessage() + "\nResponse was: " + entity);
  }
}

代码示例来源:origin: tadglines/Socket.IO-Java

@Override
public void onConnect(SocketIOOutbound outbound) {
  if (LOGGER.isLoggable(Level.FINE))
    LOGGER.fine(this + " connected.");
  this.outbound = outbound;
  try {
    send(new JSONObject().put("type", MessageType.ACK));
  } catch (JSONException e) {
    throw new RuntimeException(e.getMessage(), e);
  }
}

代码示例来源: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: GluuFederation/oxAuth

@Parameters({"jwksPath"})
@Test
public void requestJwks(final String jwksPath) throws Exception {
  Builder request = ResteasyClientBuilder.newClient().target(url.toString() + jwksPath).request();
  request.header("Accept", MediaType.APPLICATION_JSON);
  Response response = request.get();
  String entity = response.readEntity(String.class);
  showResponse("requestJwks", response, entity);
  assertEquals(response.getStatus(), 200, "Unexpected response code.");
  try {
    JSONObject jsonObj = new JSONObject(entity);
    assertTrue(jsonObj.has(JSON_WEB_KEY_SET), "Unexpected result: keys not found");
    JSONArray keys = jsonObj.getJSONArray(JSON_WEB_KEY_SET);
    assertNotNull(keys, "Unexpected result: keys is null");
    assertTrue(keys.length() > 0, "Unexpected result: keys is empty");
  } catch (JSONException e) {
    e.printStackTrace();
    fail(e.getMessage());
  }
}

代码示例来源:origin: com.couchbase.client/couchbase-client

/**
 * Parse a raw bucket config string into a {@link Bucket} configuration.
 *
 * @param bucketJson the raw JSON.
 * @return the parsed configuration.
 * @throws ParseException if the JSON could not be parsed properly.
 */
public Bucket parseBucket(String bucketJson) throws ParseException {
 try {
  return parseBucketFromJSON(new JSONObject(bucketJson), null);
 } catch (JSONException e) {
  throw new ParseException(e.getMessage(), 0);
 }
}

代码示例来源:origin: gentics/mesh

public JSONObject getAuthTokenResponse() {
  JSONObject node = new JSONObject();
  try {
    node.put("token",
      "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyVXVpZCI6IlVVSURPRlVTRVIxIiwiZXhwIjoxNDY5MTE3MjQ3LCJpYXQiOjE0NjkxMTM2NDd9.i1u4RMs4K7zBkGhmcpp1P79Wpz2UQYJkZKJTVdFp_iU=");
  } catch (JSONException e) {
    e.printStackTrace();
  }
  return node;
}

代码示例来源:origin: com.couchbase.client/couchbase-client

/**
 * Parses a given /pools/{pool} JSON for the buckets URI.
 *
 * @param pool the actual pool object to attach to.
 * @param poolsJson the raw JSON for the pool response.
 * @throws ParseException if the JSON could not be parsed properly.
 */
public void parsePool(final Pool pool, final String poolsJson)
 throws ParseException {
 try {
  JSONObject buckets = new JSONObject(poolsJson).getJSONObject("buckets");
  URI bucketsUri = new URI(buckets.getString("uri"));
  pool.setBucketsUri(bucketsUri);
 } catch (JSONException e) {
  throw new ParseException(e.getMessage(), 0);
 } catch (URISyntaxException e) {
  throw new ParseException(e.getMessage(), 0);
 }
}

代码示例来源:origin: com.couchbase.client/couchbase-client

/**
 * Helper method to create a {@link List} of view server URLs.
 *
 * @param nodes the raw JSON nodes.
 * @return a populated list of URLs.
 * @throws JSONException if parsing the JSON was not successful.
 */
private List<URL> populateViewServers(JSONArray nodes) throws JSONException {
 int nodeSize = nodes.length();
 List<URL> nodeUrls = new ArrayList<URL>(nodeSize);
 for (int i = 0; i < nodeSize; i++) {
  JSONObject node = nodes.getJSONObject(i);
  if (node.has("couchApiBase")) {
   try {
    nodeUrls.add(new URL(node.getString("couchApiBase")));
   } catch (MalformedURLException e) {
    throw new JSONException("Got bad couchApiBase URL from config");
   }
  }
 }
 return nodeUrls;
}

代码示例来源:origin: GluuFederation/oxAuth

/**
 * Constructs an token revocation response.
 */
public TokenRevocationResponse(ClientResponse<String> clientResponse) {
  super(clientResponse);
  if (StringUtils.isNotBlank(entity)) {
    try {
      JSONObject jsonObj = new JSONObject(entity);
      if (jsonObj.has("error")) {
        errorType = TokenRevocationErrorResponseType.getByValue(jsonObj.getString("error"));
      }
      if (jsonObj.has("error_description")) {
        errorDescription = jsonObj.getString("error_description");
      }
      if (jsonObj.has("error_uri")) {
        errorUri = jsonObj.getString("error_uri");
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
}

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

public Object generateFieldValueForJson(Object rawValue) throws JSONException {
    if (rawValue == null) {
      return JSONObject.NULL;
    } else if (rawValue instanceof ComplexIssueInputFieldValue) {
      return generate((ComplexIssueInputFieldValue) rawValue);
    } else if (rawValue instanceof Iterable) {
      // array with values
      final JSONArray array = new JSONArray();
      for (Object value : (Iterable) rawValue) {
        array.put(generateFieldValueForJson(value));
      }
      return array;
    } else if (rawValue instanceof CharSequence) {
      return rawValue.toString();
    } else if (rawValue instanceof Number) {
      return rawValue;
    } else {
      throw new JSONException("Cannot generate value - unknown type for me: " + rawValue.getClass());
    }
  }
}

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

public void setTags(Set<String> tags)
{
 if (tags == null || tags.isEmpty()) {
  throw new IllegalArgumentException("tags can't be null or empty.");
 }
 try {
  JSONArray tagArray = new JSONArray(tags);
  schema.put(FIELD_SCHEMA_TAGS, tagArray);
 } catch (JSONException e) {
  Preconditions.checkState(false, e.getMessage());
  throw new RuntimeException(e);
 }
 schemaJSON = schema.toString();
}

代码示例来源:origin: com.peterphi.user-manager/user-manager-api

public static OAuth2TokenResponse decode(final String json)
{
  try
  {
    final JSONObject obj = new JSONObject(json);
    final int expiresIn = obj.has("expires_in") ? obj.getInt("expires_in") : 0;
    // Set expires 1m before expires_in
    final Date expires;
    if (expiresIn == 0)
      expires = new Date(System.currentTimeMillis() + ((expiresIn - 60) * 1000));
    else
      expires = null;
    return new OAuth2TokenResponse(getString(obj, "access_token", null),
                    getString(obj, "refresh_token", null),
                    expires,
                    getString(obj, "error", null));
  }
  catch (JSONException e)
  {
    throw new RuntimeException("Unable to deserialise OAuth2TokenResponse: " + e.getMessage(), e);
  }
}

代码示例来源:origin: com.netflix.dyno/dyno-contrib

public ConnectionPoolConfigurationPublisher createPublisher(String applicationName, String clusterName, ConnectionPoolConfiguration config) {
  if (config.getConfigurationPublisherConfig() != null) {
    try {
      JSONObject json = new JSONObject(config.getConfigurationPublisherConfig());
      String vip = json.getString("vip");
      if (vip != null) {
        String type = json.getString("type");
        if (type != null) {
          ConnectionPoolConfigurationPublisher.PublisherType publisherType =
              ConnectionPoolConfigurationPublisher.PublisherType.valueOf(type.toUpperCase(Locale.ENGLISH));
          if (ConnectionPoolConfigurationPublisher.PublisherType.ELASTIC == publisherType) {
            return new ElasticConnectionPoolConfigurationPublisher(applicationName, clusterName, vip, config);
          }
        }
      }
    } catch (JSONException e) {
      Logger.warn("Invalid json specified for config publisher: " + e.getMessage());
    }
  }
  return null;
}

代码示例来源:origin: GluuFederation/oxAuth

@Parameters({"registerPath"})
@Test
public void requestClientRegistrationFail1(final String registerPath) throws Exception {
  Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
  String registerRequestContent = null;
  try {
    RegisterRequest registerRequest = new RegisterRequest(null, null, null);
    registerRequestContent = registerRequest.getJSONParameters().toString(4);
  } catch (JSONException e) {
    e.printStackTrace();
    fail(e.getMessage());
  }
  Response response = request.post(Entity.json(registerRequestContent));
  String entity = response.readEntity(String.class);
  showResponse("requestClientRegistrationFail 1", response, entity);
  assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
  TestUtil.assertErrorResponse(entity);
}

代码示例来源:origin: org.codehaus.jettison/jettison

value = convention.convertToJSONPrimitive((String)value);
Object old = object.opt(property.getKey());
try {
  if(old != null) {
      values = (JSONArray)old;
    } else {
      values = new JSONArray();
      values.put(old);
    values.put(value);
    object.put(property.getKey(), values);
  } else if(getSerializedAsArrays().contains(getPropertyArrayKey(property))) {
    JSONArray values = new JSONArray();
      values.put(value);
    object.put(property.getKey(), values);
  } else {
  e.printStackTrace();

相关文章