本文整理汇总了Java中org.json.simple.JSONObject类的典型用法代码示例。如果您正苦于以下问题:Java JSONObject类的具体用法?Java JSONObject怎么用?Java JSONObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JSONObject类属于org.json.simple包,在下文中一共展示了JSONObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: fillAnnotations
import org.json.simple.JSONObject; //导入依赖的package包/类
private void fillAnnotations(@SuppressWarnings("unused") Logger logger, Section sec, JSONObject json, Map<String,Element> eltMap) {
JSONArray catanns = (JSONArray) json.get("catanns");
if (catanns == null) {
return;
}
Layer annotations = sec.ensureLayer(annotationsLayerName);
for (Object o : catanns) {
JSONObject ca = (JSONObject) o;
String id = (String) ca.get("id");
JSONObject span = (JSONObject) ca.get("span");
int begin = (int) (long) span.get("begin");
int end = (int) (long) span.get("end");
String category = (String) ca.get("category");
Layer layer = sec.ensureLayer(category);
Annotation a = new Annotation(this, layer, begin, end);
annotations.add(a);
a.addFeature("id", id);
a.addFeature("category", category);
eltMap.put(id, a);
}
}
示例2: openWebSocket
import org.json.simple.JSONObject; //导入依赖的package包/类
private void openWebSocket(String url) {
try {
ws = new WebSocketFactory().createSocket(url).addListener(new WebSocketAdapter() {
@Override
public void onTextMessage(WebSocket websocket, String message) {
JsonObject json = Jsoner.deserialize(message, new JsonObject());
if (json.containsKey("type")) {
if (json.getString(Jsoner.mintJsonKey("type", null)).equals("message")) {
//TODO: Figure out if there is a way to get the user id of a bot instead of just using janet's
SlackUser info = json.containsKey("bot_id") ? getUserInfo("U2Y19AVNJ") : getUserInfo(json.getString(Jsoner.mintJsonKey("user", null)));
String text = json.getString(Jsoner.mintJsonKey("text", null));
while (text.contains("<") && text.contains(">"))
text = text.split("<@")[0] + '@' + getUserInfo(text.split("<@")[1].split(">:")[0]).getName() + ':' + text.split("<@")[1].split(">:")[1];
String channel = json.getString(Jsoner.mintJsonKey("channel", null));
if (channel.startsWith("D")) //Direct Message
sendSlackChat(info, text, true);
else if (channel.startsWith("C") || channel.startsWith("G")) //Channel or Group
sendSlackChat(info, text, false);
}
}
}
}).connect();
} catch (Exception ignored) {
}
}
示例3: handleWeatherMessage
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* handleWeatherMessage takes received telemetry message and processes it to be printed to command line.
* @param msg Telemetry message received through hono server.
*/
private void handleWeatherMessage(final Message msg) {
final Section body = msg.getBody();
//Ensures that message is Data (type of AMQP messaging). Otherwise exits method.
if (!(body instanceof Data))
return;
//Gets deviceID.
final String deviceID = MessageHelper.getDeviceId(msg);
//Creates JSON parser to read input telemetry weather data. Prints data to console output.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(((Data) msg.getBody()).getValue().toString());
JSONObject payload = (JSONObject) obj;
System.out.println(new StringBuilder("Device: ").append(deviceID).append("; Location: ").
append(payload.get("location")).append("; Temperature:").append(payload.get("temperature")));
} catch (ParseException e) {
System.out.println("Data was not sent in a readable way. Check telemetry input.");
e.printStackTrace();
}
}
示例4: encodeToJSONObject
import org.json.simple.JSONObject; //导入依赖的package包/类
public static JSONObject
encodeToJSONObject(
Map<Object,Object> b_map )
{
if ( b_map == null ){
return( null );
}
JSONObject j_map = new JSONObject();
for ( Map.Entry<Object,Object> entry: b_map.entrySet()){
Object key = entry.getKey();
Object val = entry.getValue();
j_map.put((String)key, encodeToJSONGeneric( val ));
}
return( j_map );
}
示例5: CallCreate
import org.json.simple.JSONObject; //导入依赖的package包/类
public CallCreate(JSONObject callCreateJSON) {
String data = callCreateJSON.get("data").toString();
String destination = callCreateJSON.get("destination").toString();
String gasLimit = callCreateJSON.get("gasLimit").toString();
String value = callCreateJSON.get("value").toString();
if (data != null && data.length() > 2)
this.data = Hex.decode(data.substring(2));
else
this.data = ByteUtil.EMPTY_BYTE_ARRAY;
this.destination = Hex.decode(destination);
this.gasLimit = ByteUtil.bigIntegerToBytes(TestCase.toBigInt(gasLimit));
this.value = ByteUtil.bigIntegerToBytes(TestCase.toBigInt(value));
}
示例6: JSONObject
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* Cellの更新の$formatがjsonのテスト.
*/
@SuppressWarnings("unchecked")
@Test
public final void Cellの更新の$formatがjsonのテスト() {
// Cellを更新
// リクエストヘッダをセット
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
headers.put(HttpHeaders.IF_MATCH, "*");
// リクエストボディを生成
JSONObject requestBody = new JSONObject();
requestBody.put("Name", cellName);
res = updateCellQuery(headers, requestBody, QUERY_FORMAT_JSON);
// Cell更新のレスポンスチェック
// TODO $formatのチェックが実装されたら変更する必要がある
assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode());
}
示例7: getPluginData
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
示例8: postPlugin
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* 发送服务器数据到统计网页
*/
private void postPlugin() throws IOException {
// 服务器数据获取
final String pluginname = Uranium.name;
final String tmposarch = System.getProperty("os.arch");
final Map<String, Object> data = new HashMap();
data.put("guid", guid);
data.put("server_version", Bukkit.getVersion());
data.put("server_port", Bukkit.getServer().getPort());
data.put("server_tps", FMLCommonHandler.instance().getMinecraftServerInstance().recentTps[1]);
data.put("plugin_version", Uranium.getCurrentVersion());
data.put("players_online", Bukkit.getServer().getOnlinePlayers().size());
data.put("os_name", System.getProperty("os.name"));
data.put("os_arch", tmposarch.equalsIgnoreCase("amd64") ? "x86_64" : tmposarch);
data.put("os_version", System.getProperty("os.version"));
data.put("os_usemem", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024);
data.put("os_cores", Runtime.getRuntime().availableProcessors());
data.put("auth_mode", Bukkit.getServer().getOnlineMode() ? 1 : 0);
data.put("java_version", System.getProperty("java.version"));
final String jsondata = "Info=" + JSONValue.toJSONString(data);
final String url = String.format("http://api.yumc.pw/I/P/S/V/%s/P/%s", REVISION, URLEncoder.encode(pluginname, "UTF-8"));
print("Plugin: " + pluginname + " Send Data To CityCraft Data Center");
print("Address: " + url);
print("Data: " + jsondata);
// 发送数据
final JSONObject result = (JSONObject) JSONValue.parse(postData(url, jsondata));
print("Plugin: " + pluginname + " Recover Data From CityCraft Data Center: " + result.get("info"));
}
示例9: Transaction
import org.json.simple.JSONObject; //导入依赖的package包/类
public Transaction(JSONObject callCreateJSON) {
String dataStr = callCreateJSON.get("data").toString();
String gasLimitStr = Utils.parseUnidentifiedBase(callCreateJSON.get("gasLimit").toString());
String gasPriceStr = Utils.parseUnidentifiedBase(callCreateJSON.get("gasPrice").toString());
String nonceStr = callCreateJSON.get("nonce").toString();
String secretKeyStr = callCreateJSON.get("secretKey").toString();
String toStr = callCreateJSON.get("to").toString();
String valueStr = callCreateJSON.get("value").toString();
this.data = Utils.parseData(dataStr);
this.gasLimit = !gasLimitStr.isEmpty() ? new BigInteger(gasLimitStr).toByteArray() : new byte[]{0};
this.gasPrice = Utils.parseLong(gasPriceStr);
this.nonce = Utils.parseLong(nonceStr);
this.secretKey = Utils.parseData(secretKeyStr);
this.to = Utils.parseData(toStr);
this.value = Utils.parseLong(valueStr);
}
示例10: JSONObject
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* ログファイルに対するGETで200が返却されること.
*/
@SuppressWarnings("unchecked")
@Test
public final void ログファイルに対するGETで200が返却されること() {
JSONObject body = new JSONObject();
body.put("level", "INFO");
body.put("action", "POST");
body.put("object", "ObjectData");
body.put("result", "resultData");
CellUtils.event(MASTER_TOKEN_NAME, HttpStatus.SC_OK, Setup.TEST_CELL1, body.toJSONString());
TResponse response = Http.request("cell/log-get.txt")
.with("METHOD", HttpMethod.GET)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("cellPath", Setup.TEST_CELL1)
.with("collection", CURRENT_COLLECTION)
.with("fileName", DEFAULT_LOG)
.with("ifNoneMatch", "*")
.returns();
response.debug();
String responseBody = response.getBody();
assertTrue(0 < responseBody.length());
response.statusCode(HttpStatus.SC_OK);
}
示例11: getPerson
import org.json.simple.JSONObject; //导入依赖的package包/类
public Person getPerson(String personId, int expectedStatus) throws PublicApiException
{
HttpResponse response = getSingle("people", personId, null, null, "Failed to get person", expectedStatus);
if(logger.isDebugEnabled())
{
logger.debug(response);
}
System.out.println(response);
if (response != null && response.getJsonResponse() != null)
{
JSONObject entry = (JSONObject) response.getJsonResponse().get("entry");
if (entry != null)
{
return Person.parsePerson(entry);
}
}
return null;
}
示例12: getChartData
import org.json.simple.JSONObject; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@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;
}
示例13: getAllNPCs
import org.json.simple.JSONObject; //导入依赖的package包/类
public static ArrayList<String> getAllNPCs() {
ArrayList<String> a = new ArrayList<>();
try {
File file = plugin.getPath().getAbsoluteFile();
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(file.getPath()));
JSONObject jsonObject = (JSONObject) parsed;
JSONArray npcsArray = (JSONArray) jsonObject.get("npcs");
for (Object npc : npcsArray) {
a.add((String) ((JSONObject) npc).get("name"));
}
} catch (ParseException | IOException e) {
e.printStackTrace();
}
return a;
}
示例14: getSkinUrl
import org.json.simple.JSONObject; //导入依赖的package包/类
public String getSkinUrl(GameProfile prof) throws ParseException {
Collection<Property> ps = prof.getProperties().get("textures");
if (ps == null || ps.isEmpty()) {
return null;
} else {
Property p = Iterators.getLast(ps.iterator());
JSONObject obj = (JSONObject) new JSONParser().parse(
new String(Base64.getDecoder().decode(p.getValue())));
obj = ((JSONObject) obj.get("textures"));
obj = ((JSONObject) obj.get("SKIN"));
return (String) obj.get("url");
}
}
示例15: refreshAccessToken
import org.json.simple.JSONObject; //导入依赖的package包/类
/**
* Refreshes the Access Token of the currently used account
*/
public void refreshAccessToken() {
this.updateHTTPParameter();
JodelHTTPResponse requestResponse = this.httpAction.getNewAccessToken();
if (requestResponse.responseCode == 200) {
String responseMessage = requestResponse.responseMessage;
JSONParser parser = new JSONParser();
try {
JSONObject responseJson = (JSONObject) parser.parse(responseMessage);
this.accessToken = responseJson.get("access_token").toString();
this.expirationDate = responseJson.get("expiration_date").toString();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}