當前位置: 首頁>>代碼示例>>Java>>正文


Java JSONObject類代碼示例

本文整理匯總了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);
	}
}
 
開發者ID:Bibliome,項目名稱:alvisnlp,代碼行數:22,代碼來源:GeniaJSONReader.java

示例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) {
    }
}
 
開發者ID:pupnewfster,項目名稱:Necessities,代碼行數:26,代碼來源:JanetSlack.java

示例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();
    }
}
 
開發者ID:rhiot,項目名稱:hono-weather-demo,代碼行數:24,代碼來源:WeatherDataConsumer.java

示例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 );
}
 
開發者ID:BiglySoftware,項目名稱:BiglyBT,代碼行數:22,代碼來源:BEncoder.java

示例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));
    }
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:17,代碼來源:CallCreate.java

示例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());
}
 
開發者ID:personium,項目名稱:personium-core,代碼行數:24,代碼來源:UpdateTest.java

示例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;
}
 
開發者ID:Ladinn,項目名稱:JavaShell,代碼行數:28,代碼來源:Metrics.java

示例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"));
}
 
開發者ID:UraniumMC,項目名稱:Uranium,代碼行數:34,代碼來源:YUMCStatistics.java

示例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);
    }
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:19,代碼來源:Transaction.java

示例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);
}
 
開發者ID:personium,項目名稱:personium-core,代碼行數:28,代碼來源:LogTest.java

示例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;
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:21,代碼來源:PublicApiClient.java

示例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;
      }
 
開發者ID:EverCraft,項目名稱:ServerConnect,代碼行數:26,代碼來源:Metrics.java

示例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;
}
 
開發者ID:Warvale,項目名稱:Locked,代碼行數:18,代碼來源:MerchantManager.java

示例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");
    }
}
 
開發者ID:devcexx,項目名稱:libtrails,代碼行數:17,代碼來源:SkinDownloader.java

示例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();
        }
    }
}
 
開發者ID:fr31b3u73r,項目名稱:JodelAPI,代碼行數:20,代碼來源:JodelAccount.java


注:本文中的org.json.simple.JSONObject類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。