下面列出了怎么用org.json.simple.JSONObject的API类实例代码及写法,或者点击链接到github查看源代码。
private void crawlComputeOfferings() {
/* iaas section */
String computeQuery = "https://cloudharmony.com/api/services?"
+ "api-key=" + API_KEY + "&"
+ "serviceTypes=compute";
JSONObject resp = (JSONObject) query(computeQuery);
if(resp == null) {
return;
}
JSONArray computes = (JSONArray) resp.get("ids");
Iterator<String> it = computes.iterator();
while (it.hasNext()) {
try {
String serviceId = it.next();
CloudHarmonyService chService = getService(serviceId, CloudTypes.IAAS);
if (chService != null)
generateOfferings(chService);
} catch(Exception ex) {
log.warn(ex.getMessage());
}
}
}
/**
* Tries to fetch the current display name for the user
*
* @param id the id of the user to check
* @return the current display name of that user
* @throws IOException if something goes wrong
* @throws VoxelGameLibException if the user has no display name
*/
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
System.out.println(url.toString());
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
if (scanner.hasNext()) {
String json = scanner.nextLine();
try {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
if (json.length() > 0) {
return (String) ((JSONObject) jsonArray.get(0)).get("name");
}
} catch (ParseException ignore) {
}
}
throw new VoxelGameLibException("User has no name! " + id);
}
@Test
public void testReadMultiLineWithErrors() throws Exception {
Syslog3164Parser parser = new Syslog3164Parser();
Map<String, Object> config = new HashMap<>();
parser.configure(config);
StringBuilder builder = new StringBuilder();
builder
.append("HEREWEGO!!!!\n")
.append(SYSLOG_LINE_ALL)
.append("\n")
.append(SYSLOG_LINE_MISSING)
.append("\n")
.append("BOOM!\n")
.append(SYSLOG_LINE_ALL)
.append("\nOHMY!");
Optional<MessageParserResult<JSONObject>> output = parser.parseOptionalResult(builder.toString().getBytes(
StandardCharsets.UTF_8));
assertTrue(output.isPresent());
assertEquals(3,output.get().getMessages().size());
assertEquals(3,output.get().getMessageThrowables().size());
}
/**
* 非同期でドキュメントを検索. <br />
* Queryの指定方法をMapで直接記述せずにQueryBuilderにするため、非推奨とする.
* @param index インデックス名
* @param routingId routingId
* @param query クエリ情報
* @return 非同期応答
*/
public ActionFuture<SearchResponse> asyncSearch(
String index,
String routingId,
Map<String, Object> query) {
SearchRequest req = new SearchRequest(index).searchType(SearchType.DEFAULT);
if (query != null) {
req.source(query);
}
if (routingFlag) {
req = req.routing(routingId);
}
ActionFuture<SearchResponse> ret = esTransportClient.search(req);
this.fireEvent(Event.afterRequest, index, null, null, JSONObject.toJSONString(query), "Search");
return ret;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
/**
* セルレベルPROPPATCHをオーナーが違うユニットローカルユニットユーザトークンで実行不可なことを確認.
* @throws TokenParseException トークンパースエラー
*/
@Test
public final void セルレベルPROPPATCHをオーナーが違うユニットローカルユニットユーザトークンで実行不可なことを確認() throws TokenParseException {
// アカウントにユニット昇格権限付与
DavResourceUtils.setProppatch(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME,
"cell/proppatch-uluut.txt", HttpStatus.SC_MULTI_STATUS);
// パスワード認証でのユニット昇格
TResponse res = Http.request("authnUnit/password-uluut.txt")
.with("remoteCell", Setup.TEST_CELL1)
.with("username", "account1")
.with("password", "password1")
.returns()
.statusCode(HttpStatus.SC_OK);
JSONObject json = res.bodyAsJson();
String uluutString = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN);
// アカウントにユニット昇格権限付与
DavResourceUtils.setProppatch(Setup.TEST_CELL2, uluutString,
"cell/proppatch-uluut.txt", HttpStatus.SC_FORBIDDEN);
}
public static Player loadPlayer() {
try {
FileHandle handle = Gdx.files.external("player.save");
if (!handle.exists()) {
// not saved player yet
return null;
}
String JSONString = handle.readString();
JSONObject playerInfo = (JSONObject) new JSONParser().parse(JSONString);
JSONObject playerPosition = (JSONObject) playerInfo.get("playerPosition");
Player player = new Player(Float.parseFloat(playerPosition.get("x").toString()), Float.parseFloat(playerPosition.get("y").toString()));
JSONObject jsonInventory = (JSONObject) playerInfo.get("playerInventory");
Inventory inventory = JSONConverter.getInventoryFromJSON(jsonInventory);
player.setInventory(inventory);
return player;
} catch(ParseException ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
@Override
public String loginApplication(String loginToken) {
if (loginToken != null && !loginToken.trim().equals("")) {
String response = null;
response = transport.execute(JSONRequestConstants.JSON_SYSTEM_LOGIN_APPLICATION + loginToken);
JSONObject responseObj = handler.toJSONObject(response);
if (handler.checkResponse(responseObj)) {
JSONObject obj = handler.getResultJSONObject(responseObj);
String tokenStr = null;
if (obj != null && obj.get(JSONApiResponseKeysEnum.SYSTEM_LOGIN.getKey()) != null) {
tokenStr = obj.get(JSONApiResponseKeysEnum.SYSTEM_LOGIN.getKey()).toString();
}
if (tokenStr != null) {
return tokenStr;
}
}
}
return null;
}
public static Object getMessagesFromResponse(String responseStr, String node) {
Object msgObject = null;
if (responseStr == null || responseStr.equalsIgnoreCase(""))
return msgObject;
try {
JSONObject responseObj = (JSONObject) JSONValue
.parseWithException(responseStr);
if (responseObj != null) {
JSONObject dataObj = (JSONObject) responseObj
.get(ConstantsForTest.DATA);
if (dataObj != null) {
msgObject = dataObj.get(node);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgObject;
}
@SuppressWarnings("rawtypes")
@Test
public void testDnsBroMessage() throws ParseException {
Map rawMessageMap = (Map) jsonParser.parse(dnsBroMessage);
JSONObject rawJson = (JSONObject) rawMessageMap.get(rawMessageMap.keySet().iterator().next());
JSONObject broJson = broParser.parse(dnsBroMessage.getBytes(StandardCharsets.UTF_8)).get(0);
String expectedBroTimestamp = "1402308259.609";
assertEquals(broJson.get("bro_timestamp"), expectedBroTimestamp);
String expectedTimestamp = "1402308259609";
assertEquals(broJson.get("timestamp").toString(), expectedTimestamp);
assertEquals(broJson.get("ip_src_addr").toString(), rawJson.get("id.orig_h").toString());
assertEquals(broJson.get("ip_dst_addr").toString(), rawJson.get("id.resp_h").toString());
assertEquals(broJson.get("ip_src_port").toString(), rawJson.get("id.orig_p").toString());
assertEquals(broJson.get("ip_dst_port").toString(), rawJson.get("id.resp_p").toString());
assertTrue(broJson.get("original_string").toString().startsWith(rawMessageMap.keySet().iterator().next().toString().toUpperCase()));
assertEquals(broJson.get("qtype").toString(), rawJson.get("qtype").toString());
assertEquals(broJson.get("trans_id").toString(), rawJson.get("trans_id").toString());
assertTrue(broJson.get("original_string").toString().startsWith("DNS"));
}
/**
* ユーザーデータに更新を実行し、レスポンスコードをチェックする.
* @param token トークン
* @param code 期待するレスポンスコード
* @return レスポンス
*/
@SuppressWarnings("unchecked")
public static TResponse update(String token, int code) {
JSONObject body = new JSONObject();
body.put("__id", "auth_test");
body.put("prop", "prop");
TResponse res = Http.request("box/odatacol/update.txt")
.with("cell", "testcell1")
.with("box", "box1")
.with("collection", "setodata")
.with("entityType", "Price")
.with("id", "auth_test")
.with("accept", MediaType.APPLICATION_JSON)
.with("contentType", MediaType.APPLICATION_JSON)
.with("token", token)
.with("ifMatch", "*")
.with("body", body.toJSONString())
.returns()
.statusCode(code)
.debug();
return res;
}
/**
* Add a custom trigger sentence for a given language to the collection with predefined parameters, e.g. "Bring me home" with "location=home".
* If the service registers itself as a custom services this will be used.
* @param sentence - a sample sentence
* @param language - language code for this sentence
* @param normParameters - predefined parameters for this sentence in normalized format (not extracted yet)
*/
public ServiceInfo addCustomTriggerSentenceWithNormalizedParameters(String sentence, String language, JSONObject normParameters){
List<String> list = customTriggerSentences.get(language);
if (list == null){
list = new ArrayList<>();
customTriggerSentences.put(language, list);
}
//tag parameters
for (Object keyObj : normParameters.keySet()){
String key = (String) keyObj;
JSON.put(normParameters, key, Interview.INPUT_NORM + JSON.getString(normParameters, key));
}
//build sentence + cmdSummary
sentence = sentence + ";;" + Converters.makeCommandSummary(this.intendedCommand, normParameters);
list.add(sentence);
return this;
}
public void loadMCLeaksValues(Set<RawMCLeaksResult> values, boolean truncate) throws StorageException {
try (Jedis redis = pool.getResource()) {
if (truncate) {
deleteNamespace(redis, prefix + "mcleaks_values:");
}
long max = 0;
for (RawMCLeaksResult r : values) {
max = Math.max(max, r.getID());
JSONObject obj = new JSONObject();
obj.put("playerID", r.getLongPlayerID());
obj.put("result", r.getValue());
obj.put("created", r.getCreated());
redis.set(prefix + "mcleaks_values:" + r.getID(), obj.toJSONString());
obj.remove("playerID");
obj.put("id", r.getID());
redis.rpush(prefix + "mcleaks_values:player:" + r.getLongPlayerID(), obj.toJSONString());
}
redis.set(prefix + "mcleaks_values:idx", String.valueOf(max));
} catch (JedisException ex) {
throw new StorageException(isAutomaticallyRecoverable(ex), ex);
}
}
/**
* Propertyを更新する.
* @param token トークン
* @param cell セル名
* @param box ボックス名
* @param collection コレクション名
* @param srcPropertyName 更新前Property名
* @param srcEntityTypeName 更新前EntityType名
* @param propertyName リクエストに指定するProperty名
* @param entityTypeName リクエストに指定するEntityType名
* @param type PropertyのType項目
* @param nullable PropertyのNullable項目
* @param defaultValue PropertyのDefaultValue項目
* @param collectionKind PropertyのcollectionKind項目
* @param isKey PropertyのisKey項目
* @param uniqueKey PropertyのUniqueKey項目
* @return レスポンス
*/
@SuppressWarnings("unchecked")
public static DcResponse update(
String token, String cell, String box,
String collection, String srcPropertyName,
String srcEntityTypeName, String propertyName,
String entityTypeName, String type, Boolean nullable, Object defaultValue,
String collectionKind, Boolean isKey, String uniqueKey) {
// リクエストボディの組み立て
JSONObject body = new JSONObject();
body.put("Name", propertyName);
body.put("_EntityType.Name", entityTypeName);
body.put("Type", type);
body.put("Nullable", nullable);
body.put("DefaultValue", defaultValue);
body.put("CollectionKind", collectionKind);
body.put("IsKey", isKey);
body.put("UniqueKey", uniqueKey);
return update(token, cell, box, collection, srcPropertyName, srcEntityTypeName, body);
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when
* passing a valid SQL timestamp with microseconds.
*/
@Test
public void testGetTimeInstantSQLTimestampWithMicroseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "SQL timestamp with microseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01 00:00:01.123456");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- OK - Time instant obtained for '" + metadatasJson.toJSONString() + "' is '"
+ timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue;
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
return null;
}
data.put("values", values);
return data;
}
@UrlEndpoint(url = "/toggleaux", help = "Toggle the aux pin for a PID",
parameters = {@Parameter(name = "toggle", value = "The name of the PID to toggle the pin for")})
public Response toggleAux() {
JSONObject usage = new JSONObject();
if (parameters.containsKey("toggle")) {
String pidname = parameters.get("toggle");
PID tempPID = LaunchControl.findPID(pidname);
if (tempPID != null) {
tempPID.toggleAux();
return new NanoHTTPD.Response(Status.OK, MIME_HTML,
"Updated Aux for " + pidname);
} else {
BrewServer.LOG.warning("Invalid PID: " + pidname + " provided.");
usage.put("Error", "Invalid name supplied: " + pidname);
}
}
usage.put("toggle",
"The name of the PID to toggle the aux output for");
return new Response(usage.toJSONString());
}
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
public static void main(String args[])
{
String jsonText = "{\"first_1\": 123, \"second\": [4, 5, 6], \"third\": 789}";
JSONCleaner cleaner = new JSONCleaner();
try {
//cleaner.Clean(jsonText);
Map obj=new HashMap();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
Map obj1 = new HashMap();
obj1.put("sourcefile", obj);
JSONObject json = new JSONObject(obj1);
System.out.println(json);
System.out.print(jsonText);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @return an array of offerings successfully translated into SeaClouds offering format
*/
private void getOfferings() {
File offeringsDirectory = new File(paasifyRepositoryDirecory + "/profiles");
for (File offerFile : offeringsDirectory.listFiles()) {
try {
if (offerFile.isFile() && isJSON(offerFile)) {
FileReader fr = new FileReader(offerFile);
JSONObject obj =(JSONObject) jsonParser.parse(fr);
Offering offering = getOfferingFromJSON(obj);
fr.close();
if (offering != null)
addOffering(offering);
}
} catch (IOException ioe) {
log.error("IOException");
log.error(ioe.getMessage());
} catch (ParseException pe) {
log.error("ParseException");
log.error(pe.getMessage());
}
}
}
public void sendPostVPN(UUID messageID, long id, long longIPID, String ip, Optional<Boolean> cascade, Optional<Double> consensus, long created) throws MessagingException {
if (messageID == null) {
throw new IllegalArgumentException("messageID cannot be null.");
}
if (ip == null) {
throw new IllegalArgumentException("ip cannot be null.");
}
if (!ValidationUtil.isValidIp(ip)) {
throw new IllegalArgumentException("ip is invalid.");
}
if (cascade == null) {
throw new IllegalArgumentException("cascade cannot be null.");
}
if (consensus == null) {
throw new IllegalArgumentException("consensus cannot be null.");
}
try (Jedis redis = pool.getResource()) {
JSONObject obj = createJSON(messageID);
obj.put("id", id);
obj.put("longIPID", longIPID);
obj.put("ip", ip);
obj.put("cascade", cascade.orElse(null));
obj.put("consensus", consensus.orElse(null));
obj.put("created", created);
redis.publish("antivpn-post-vpn", obj.toJSONString());
} catch (JedisException ex) {
throw new MessagingException(isAutomaticallyRecoverable(ex), ex);
}
}
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
JSONObject requestHeader = buildRequestHeader();
JSONObject payload = new JSONObject();
payload.put("reqHeader", requestHeader);
payload.put("reqBody", requestBody);
JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
jws.setHeader("orgAlias", this.orgAlias);
jws.setHeader("token", this.token);
jws.setPayload(payload.toJSONString());
// Set the verification key
HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
jws.setKey(key);
String jwsCompactSerialization = null;
try {
jwsCompactSerialization = jws.getCompactSerialization();
} catch (JoseException e) {
e.printStackTrace();
}
this.requestToken = jwsCompactSerialization;
return jwsCompactSerialization;
}
/**
* Retrieve properties from JSON response.
* <p/>
* @param json JSON response.
* @return Properties from JSON response.
*/
private Properties parseProperties(JSONObject json) {
Properties result = new Properties();
JSONObject properties = (JSONObject)json.get("properties");
if (properties != null) {
for (Object key : properties.keySet()) {
String value = (String) properties.get(key);
result.setProperty((String)key, value);
}
}
return result;
}
public static JSONArray getJSONArray(JSONObject obj, String field) {
if (obj == null || StringUtils.isEmpty(field)) {
return null;
}
try {
return (JSONArray) obj.get(field);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unchecked")
private JSONObject extractValidationResult(ConfigValidationResult result) {
JSONObject ret = new JSONObject();
for(Map.Entry<String, List<Message>> entry : result.getMessages().entrySet()) {
ret.put(entry.getKey(), extractMessageList(entry.getValue()));
}
return ret;
}
/**
* Item to show on chat message under this text.
*
* @param item {@link ItemStack}
* @return instance of same {@link UltimateFancy}.
*/
public UltimateFancy hoverShowItem(ItemStack item) {
JSONObject jItem = parseHoverItem(item);
if (Utf8.encodedLength(jItem.toJSONString()) > 32767)
pendentElements.add(new ExtraElement("hoverEvent", parseHoverItem(new ItemStack(item.getType()))));
pendentElements.add(new ExtraElement("hoverEvent", jItem));
return this;
}
@Override
public String build(String input) {
//build default result
JSONObject itemResultJSON = new JSONObject();
JSON.add(itemResultJSON, InterviewData.VALUE, input);
JSON.add(itemResultJSON, InterviewData.VALUE_LOCAL, "");
buildSuccess = true;
return itemResultJSON.toJSONString();
}
@Override
public void writeTo(Map map, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap,
OutputStream outputStream) throws IOException, WebApplicationException {
Writer writer = new OutputStreamWriter(outputStream, Charsets.UTF_8);
JSONObject.writeJSONString(map, writer);
writer.write(ENTER);
writer.flush();
}
@NotNull
public static ReleaseInfo getLatestRelease() throws Exception {
JSONParser parser = new JSONParser();
URLConnection connection = new URL(ADCUpdater.JSON_RELEASE_INFO_URL).openConnection();
InputStreamReader reader = new InputStreamReader(connection.getInputStream());
JSONObject object = (JSONObject) parser.parse(reader);
reader.close();
connection.getInputStream().close();
return new ReleaseInfo(object);
}
@SuppressWarnings({ "unchecked", "unused" })
public JSONObject parse(byte[] msg) {
JSONObject outputMessage = new JSONObject();
String toParse = "";
try {
toParse = new String(msg, "UTF-8");
_LOG.debug("Received message: " + toParse);
parseMessage(toParse,outputMessage);
outputMessage.put("timestamp", System.currentTimeMillis());
outputMessage.put("ip_src_addr", outputMessage.remove("source_address"));
outputMessage.put("ip_src_port", outputMessage.remove("source_port"));
outputMessage.put("ip_dst_addr", outputMessage.remove("destination_address"));
outputMessage.put("ip_dst_port", outputMessage.remove("destination_port"));
outputMessage.put("protocol", outputMessage.remove("ip_protocol"));
outputMessage.put("original_string", toParse);
return outputMessage;
} catch (Exception e) {
e.printStackTrace();
_LOG.error("Failed to parse: " + toParse);
return null;
}
}