Java Code Examples for org.json.JSONObject#getInt()

The following examples show how to use org.json.JSONObject#getInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: POEAPIHelper.java    From Path-of-Leveling with MIT License 6 votes vote down vote up
public static ArrayList<CharacterInfo> getCharacters(String account) {
    Util.HttpResponse response = Util.httpToString("https://www.pathofexile.com/character-window/get-characters?accountName=" + account);
    ArrayList<CharacterInfo> result = new ArrayList<>();

    if (response.responseCode == 200) {
        JSONArray arr = new JSONArray(response.responseString);
        for (int i = 0; i < arr.length(); i++) {
            CharacterInfo ci = new CharacterInfo();
            ci.loadedFromPOEAPI = true;

            JSONObject charObj = arr.getJSONObject(i);
            ci.characterName = charObj.getString("name");
            ci.experience = charObj.getLong("experience");
            ci.level = charObj.getInt("level");
            ci.ascendancyName = charObj.getString("class");
            ci.setClassNameFromInt(charObj.getInt("classId"));
            ci.league = charObj.getString("league");
            result.add(ci);
        }
    }
    result.sort(new CharacterInfo.CharacterLeagueComparator());
    return result;
}
 
Example 2
Source File: PeerManager.java    From jelectrum with MIT License 6 votes vote down vote up
public void addPeers(JSONArray params)
  throws org.json.JSONException
{
  for(int i=0; i<params.length(); i++)
  {
    JSONObject features = params.getJSONObject(i);
    JSONObject hosts = features.getJSONObject("hosts");
    for(String hostname : JSONObject.getNames(hosts))
    {
      JSONObject host = hosts.getJSONObject(hostname);

      PeerInfo peer = new PeerInfo();
      peer.hostname = hostname;

      if (host.has("tcp_port")) { peer.tcp_port = host.getInt("tcp_port"); }
      if (host.has("ssl_port")) { peer.ssl_port = host.getInt("ssl_port"); }

      addPeerInternal(peer);

    }

  }
}
 
Example 3
Source File: VaultFile.java    From Aegis with GNU General Public License v3.0 6 votes vote down vote up
public static VaultFile fromJson(JSONObject obj) throws VaultFileException {
    try {
        if (obj.getInt("version") > VERSION) {
            throw new VaultFileException("unsupported version");
        }

        Header header = Header.fromJson(obj.getJSONObject("header"));
        if (!header.isEmpty()) {
            return new VaultFile(obj.getString("db"), header);
        }

        return new VaultFile(obj.getJSONObject("db"), header);
    } catch (JSONException e) {
        throw new VaultFileException(e);
    }
}
 
Example 4
Source File: TapasticRipper.java    From ripme with MIT License 6 votes vote down vote up
@Override
public List<String> getURLsFromPage(Document page) {
    List<String> urls = new ArrayList<>();
    String html = page.data();
    if (!html.contains("episodeList : ")) {
        LOGGER.error("No 'episodeList' found at " + this.url);
        return urls;
    }
    String jsonString = Utils.between(html, "episodeList : ", ",\n").get(0);
    JSONArray json = new JSONArray(jsonString);
    for (int i = 0; i < json.length(); i++) {
        JSONObject obj = json.getJSONObject(i);
        TapasticEpisode episode = new TapasticEpisode(i, obj.getInt("id"), obj.getString("title"));
        episodes.add(episode);
        urls.add("http://tapastic.com/episode/" + episode.id);
    }
    return urls;
}
 
Example 5
Source File: SearchActivity.java    From Twire with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<StreamInfo> getVisualElements() throws JSONException, MalformedURLException {
    List<StreamInfo> mStreams = new ArrayList<>();
    if (query != null) {
        String URL = getElementsURL(query);
        JSONObject fullDataObject = new JSONObject(Service.urlToJSONString(URL));
        String STREAMS_ARRAY = "streams";
        JSONArray mStreamsArray = fullDataObject.getJSONArray(STREAMS_ARRAY);
        String TOTAL_IN_QUERY_INT = "_total";
        int totalChannels = fullDataObject.getInt(TOTAL_IN_QUERY_INT);

        for (int i = 0; i < mStreamsArray.length(); i++) {
            JSONObject streamObject = mStreamsArray.getJSONObject(i);
            mStreams.add(JSONService.getStreamInfo(getContext(), streamObject, null, false));
        }
    }

    return mStreams;
}
 
Example 6
Source File: AuthyImporter.java    From Aegis with GNU General Public License v3.0 6 votes vote down vote up
private static VaultEntry convertEntry(JSONObject entry) throws DatabaseImporterEntryException {
    try {
        AuthyEntryInfo authyEntryInfo = new AuthyEntryInfo();
        authyEntryInfo.OriginalName = entry.optString("originalName", null);
        authyEntryInfo.OriginalIssuer = entry.optString("originalIssuer", null);
        authyEntryInfo.AccountType = entry.getString("accountType");
        authyEntryInfo.Name = entry.optString("name");

        sanitizeEntryInfo(authyEntryInfo);

        int digits = entry.getInt("digits");
        byte[] secret = Base32.decode(entry.getString("decryptedSecret"));

        OtpInfo info = new TotpInfo(secret, "SHA1", digits, 30);

        return new VaultEntry(info, authyEntryInfo.Name, authyEntryInfo.Issuer);
    } catch (OtpInfoException | JSONException | EncodingException e) {
        throw new DatabaseImporterEntryException(e, entry.toString());
    }
}
 
Example 7
Source File: SmsSingleSenderResult.java    From qcloudsms_java with MIT License 6 votes vote down vote up
@Override
public SmsSingleSenderResult parseFromHTTPResponse(HTTPResponse response)
        throws JSONException {

    JSONObject json = parseToJson(response);

    result = json.getInt("result");
    errMsg = json.getString("errmsg");
    if (json.has("sid")) {
        sid = json.getString("sid");
    }
    if (json.has("fee")) {
        fee = json.getInt("fee");
    }
    if (json.has("ext")) {
        ext = json.getString("ext");
    }

    return this;
}
 
Example 8
Source File: SampleProtocolUtil.java    From bizsocket with Apache License 2.0 5 votes vote down vote up
public static int getResCode(String s) {
    try {
        JSONObject js = new JSONObject(s);
        if (js.has("code")) {
            int code = js.getInt("code");
            return code;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 9
Source File: ProjectSelectionDialogFragment.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onResponse(Response response) throws IOException {

    try {
        showProgressDialog();
        String body = response.body().string();
        final JSONObject jsonResponse = new JSONObject(body);
        if (!response.isSuccessful()) {
            final JSONObject jsonError = jsonResponse.getJSONObject("error");
            final int errorCode = jsonError.getInt("code");
            final String message = jsonError.getString("message");
            ProximityApiErrorDialogFragment errorDialogFragment;
            hideProgressDialog();
            switch (errorCode) {
                case Utils.ERROR_UNAUTHORIZED:
                    mServerAuthCode = ((OnProjectSelectionListener)getParentFragment()).getServerAuthCode();
                    if(mServerAuthCode != null) {
                        final String refreshToken = mContext.getSharedPreferences(Utils.ACCESS_TOKEN_INFO, Context.MODE_PRIVATE).getString(Utils.REFRESH_TOKEN, "");
                        if(!refreshToken.isEmpty())
                            new RefreshAccessTokenTask(mRefreshAccessTokenCallback, refreshToken, getString(R.string.server_client_id), mServerAuthCode).execute();
                    } else {
                        dismiss();
                        ((OnProjectSelectionListener)getParentFragment()).displayGoogleSignInDialog();
                    }
                    return;
                default:
                    errorDialogFragment = ProximityApiErrorDialogFragment.newInstance(String.valueOf(errorCode), message, "");
                    errorDialogFragment.show(getChildFragmentManager(), null);
                    return;
            }
        }
        Log.v(Utils.TAG, jsonResponse.toString());
        parseProjectsFromResponse(jsonResponse);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: OrderFragment.java    From elemeimitate with Apache License 2.0 5 votes vote down vote up
public List<HashMap<String,Object>> getOrderList(String url,String account){
  	List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
  	
  	//同步加载的类
  	SyncHttp syncHttp = new SyncHttp();
  	
  	String params = "account=" + account;
  	
  	try {
	String retStr = syncHttp.httpGet(url, params);	
	JSONObject jsonObject = new JSONObject(retStr);
	
	int ret = jsonObject.getInt("ret");
	if(ret == 0){
		JSONObject dataObject = jsonObject.getJSONObject("data");
		int totalNum = dataObject.getInt("totalNum");
		if(totalNum > 0){
			JSONArray orderlist = dataObject.getJSONArray("orderList");
			for(int i = 0;i<orderlist.length();i++){
				JSONObject orderMap = (JSONObject)orderlist.opt(i);
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("picPath", orderMap.getString("picPath"));
				map.put("name", orderMap.getString("name"));
				map.put("amount", orderMap.getInt("amount"));
				map.put("order_time", orderMap.get("order_time"));
				map.put("total_price", orderMap.getDouble("total_price"));
				map.put("status", orderMap.getString("status"));
				list.add(map);
			}
		}
	}else{
		
	}
} catch (Exception e) {
	e.printStackTrace();
}
  	return list;
  }
 
Example 11
Source File: IPMSGProtocol.java    From WifiChat with GNU General Public License v2.0 5 votes vote down vote up
public IPMSGProtocol(String paramProtocolJSON) {
    try {
        JSONObject protocolJSON = new JSONObject(paramProtocolJSON);
        packetNo = protocolJSON.getString(PACKETNO);
        commandNo = protocolJSON.getInt(COMMANDNO);
        senderIMEI = protocolJSON.getString(Users.IMEI);
        if (protocolJSON.has(ADDTYPE)) { // 若有附加信息
            String addJSONStr = null;
            if (protocolJSON.has(ADDOBJECT)) { // 若为Entity类型
                addJSONStr = protocolJSON.getString(ADDOBJECT);
            }
            else if (protocolJSON.has(ADDSTR)) { // 若为String类型
                addJSONStr = protocolJSON.getString(ADDSTR);
            }
            switch (ADDITION_TYPE.valueOf(protocolJSON.getString(ADDTYPE))) {
                case USER: // 为用户数据
                    addObject = JsonUtils.getObject(addJSONStr, Users.class);
                    break;

                case MSG: // 为消息数据
                    addObject = JsonUtils.getObject(addJSONStr, Message.class);
                    break;

                case STRING: // 为String数据
                    addStr = addJSONStr;
                    break;

                default:
                    break;
            }

        }
    }
    catch (JSONException e) {
        e.printStackTrace();
        logger.e("非标准JSON文本");
    }
}
 
Example 12
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city for one day
 *
 * @param cityId City to get the weather
 * @return userHash to be send to use
 * @note Forecast for the day
 */
public String fetchWeatherAlert(int cityId, int userId, String language, String units) {
    String cityFound;
    String responseToUser;
    try {
        String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(cityId + "") +
                ALERTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        BotLogger.info(LOGTAG, jsonObject.toString());
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
                    jsonObject.getJSONObject("city").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
            responseToUser = String.format(LocalisationService.getString("weatherAlert", language),
                    cityFound, convertListOfForecastToString(jsonObject, language, units, false));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example 13
Source File: EncryptImg.java    From pixlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws IOException, JSONException {
	
	HttpUrl httpUrl = new HttpUrl.Builder()
               .scheme("https")
               .host("api.pixlab.io")
               .addPathSegment("encrypt")
               .addQueryParameter("img", img)
               .addQueryParameter("key", key)
               .addQueryParameter("pwd", pwd)
               .build();
	
	Request requesthttp = new Request.Builder()
               .addHeader("accept", "application/json")
               .url(httpUrl)
               .build();

       Response response = client.newCall(requesthttp).execute();

	JSONObject jResponse = new JSONObject(response.body().string());
	if (jResponse.getInt("status") != 200) { 
		System.out.println("Error :: " + jResponse.getString("error"));
		System.exit(1);
	}else {
		System.out.println("Link to the decrypted picture: "+ jResponse.getString("link"));
		// use https://api.pixlab.io/decrypt with your passphrase to make it readable again
	}
}
 
Example 14
Source File: PredesignedLevel.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SneakyThrows
protected void createMobs() {
	try {
		if (mLevelDesc.has("mobs")) {
			JSONArray mobsDesc = mLevelDesc.getJSONArray("mobs");

			for (int i = 0; i < mobsDesc.length(); ++i) {
				JSONObject mobDesc = mobsDesc.optJSONObject(i);

				String kind = mobDesc.getString("kind");

				int x = mobDesc.getInt("x");
				int y = mobDesc.getInt("y");

				Char chr = Actor.findChar(cell(x,y));

				if(chr!=null) {
					ModError.doReport(kind + ": cell "+ x + "," + y + "already occupied by "+chr.getEntityKind(),
							new Exception("Mobs block error"));
					continue;
				}

				if (cellValid(x, y)) {
					Mob mob = MobFactory.mobByName(kind);
					mob.fromJson(mobDesc);
					mob.setPos(cell(x, y));
					spawnMob(mob);
				} else {
					ModError.doReport(kind+":cell "+ x + "," + y + "are outside valid level area",
							new Exception("Mobs block error"));
					continue;
				}
			}
		}
	} catch (JSONException e) {
		throw ModdingMode.modException("bad mob description",e);
	}
}
 
Example 15
Source File: TencentResponseHandler.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
	StatusLine statusLine = response.getStatusLine();
	HttpEntity entity = response.getEntity();
	String jsonStirng = (entity == null ? null : EntityUtils.toString(entity));

	
	Logger.debug("TencentResponseHandler : {}", jsonStirng);

	String dataString = null;
	try {
		JSONObject json = new JSONObject(jsonStirng);
		int res = json.getInt("ret");
		int httpStatusCode = statusLine.getStatusCode();
		switch (res) {
		case 0: // 成功返回
			if (!json.isNull("data")) {
				dataString = json.getString("data");
			} else {
				dataString = "[]";
			}

			break;
		default:
			throw TencentErrorAdaptor.parseError(json);
		}

		if (httpStatusCode >= 300) {
			throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
		}

	} catch (JSONException e) {
		throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.Tencent);
	}
	return dataString;
}
 
Example 16
Source File: BitfinexOrderBookSymbol.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * Build from JSON Array
 * @param jsonObject
 * @return
 */
public static BitfinexOrderBookSymbol fromJSON(final JSONObject jsonObject) {
	BitfinexCurrencyPair symbol = BitfinexCurrencyPair.fromSymbolString(jsonObject.getString("symbol"));
	Precision prec = Precision.valueOf(jsonObject.getString("prec"));
	Frequency freq = null;
	Integer len = null;
	if (prec != Precision.R0) {
		freq = Frequency.valueOf(jsonObject.getString("freq"));
		len = jsonObject.getInt("len");
	}
	return new BitfinexOrderBookSymbol(symbol, prec, freq, len);
}
 
Example 17
Source File: ConfCallback.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void handleChannelData(final JSONObject jsonObject) throws BitfinexClientException {
	final String status = jsonObject.getString("status");
	if (!status.equals("OK")) {
		logger.info("Got wrong state back {}", status);
	}
	// Got message: {"event":"conf","status":"OK","flags":65536}
	if (jsonObject.has("flags")) {
		final int features = jsonObject.getInt("flags");
		this.connectionFeatureConsumer.accept(features);
	} else {
		this.connectionFeatureConsumer.accept(0);
	}
}
 
Example 18
Source File: IxiConfigurationTest.java    From ict with Apache License 2.0 5 votes vote down vote up
private void validateFieldAge(JSONObject newConfiguration) {
    if (!newConfiguration.has(FIELD_AGE))
        rejectField(FIELD_AGE, "does not exist.");
    if (!(newConfiguration.get(FIELD_AGE) instanceof Integer))
        rejectField(FIELD_AGE, "is not an integer.");
    int newAge = newConfiguration.getInt(FIELD_AGE);
    if (newAge < 0 || newAge > 120)
        rejectField(FIELD_AGE, "must be in interval 0-120.");
}
 
Example 19
Source File: ANMultiAdRequestToRequestParametersTest.java    From mobile-sdk-android with Apache License 2.0 5 votes vote down vote up
private void assertMARGlobalPublisherIdInUTRequestParams() {
    String postData = getRequestParametersPostData();
    assertTrue(postData.contains("\"publisher_id\":123"));
    int publisherId = -1;
    try {
        JSONObject json = new JSONObject(postData);
        publisherId = json.getInt("publisher_id");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    assertEquals(123, publisherId);
}
 
Example 20
Source File: CoreAndroid.java    From cordova-plugin-intent with MIT License 4 votes vote down vote up
/**
 * Load the url into the webview.
 *
 * @param url
 * @param props			Properties that can be passed in to the Cordova activity (i.e. loadingDialog, wait, ...)
 * @throws JSONException
 */
public void loadUrl(String url, JSONObject props) throws JSONException {
    LOG.d("App", "App.loadUrl("+url+","+props+")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals("wait")) {
                wait = props.getInt(key);
            }
            else if (key.equalsIgnoreCase("openexternal")) {
                openExternal = props.getBoolean(key);
            }
            else if (key.equalsIgnoreCase("clearhistory")) {
                clearHistory = props.getBoolean(key);
            }
            else {
                Object value = props.get(key);
                if (value == null) {

                }
                else if (value.getClass().equals(String.class)) {
                    params.put(key, (String)value);
                }
                else if (value.getClass().equals(Boolean.class)) {
                    params.put(key, (Boolean)value);
                }
                else if (value.getClass().equals(Integer.class)) {
                    params.put(key, (Integer)value);
                }
            }
        }
    }

    // If wait property, then delay loading

    if (wait > 0) {
        try {
            synchronized(this) {
                this.wait(wait);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    this.webView.showWebPage(url, openExternal, clearHistory, params);
}