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

The following are Jave code examples for showing how to use getInt() of the org.json.JSONObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CodeMania   File: parser.java   View Source Code Vote up 7 votes
public  ArrayList<ProblemData> parseJson() throws JSONException {
    ArrayList<ProblemData> data = new ArrayList<>();
    JSONObject jsonObject  = jsondata;
   JSONObject res = jsonObject.getJSONObject("result");
   JSONArray problems = res.getJSONArray("problems");
    JSONArray stats = res.getJSONArray("problemStatistics");
    for(int i=0; i< stats.length() && i<20;i++){
        JSONObject nxtprob = problems.getJSONObject(i);
        JSONObject probstat = stats.getJSONObject(i);
        int id  = nxtprob.getInt("contestId");
        String idx = nxtprob.getString("index");
        String name = nxtprob.getString("name");
        int solvecnt = probstat.getInt("solvedCount");
        ProblemData dat = new ProblemData(id,idx,name,solvecnt);
        data.add(dat);


    }

    return data;
}
 
Example 2
Project: exchange-apis   File: HitBtcParser.java   View Source Code Vote up 6 votes
private ParserResponse parseErrorMsg(JSONObject msg, int id) {
    try {
        JSONObject error = msg.getJSONObject("error");
        int code = error.getInt("code");
        String errMsg = error.getString("message");
        String description = "";
        if (error.has("description")) {
            description = error.getString("description");
        }
        String errLog = "Error for req #" + id + ", code " + code
                + ": " + errMsg + "; " + description;
        if (notCriticalError(code)) {
            // We can recover from the error, retry connection
            return new ParserResponse(Action.RECONNECT, errLog);
        } else {
            return shutDownAction(errLog);
        }
    } catch (JSONException ex) {
        return shutDownAction("Error in HitBTC error parsing:"
                + ex.getMessage());
    }
}
 
Example 3
Project: MTweaks-KernelAdiutorMOD   File: ImportControl.java   View Source Code Vote up 6 votes
public ImportControl(String path) {
    String json = Utils.readFile(path);
    if (json != null && !json.isEmpty()) {
        try {
            JSONObject main = new JSONObject(json);
            mVersion = main.getInt("version");
            JSONObject control = main.getJSONObject("control");

            String id = control.getString("id");
            if (id != null) {
                Items.Control controlItem = Items.Control.getControl(id);
                if (controlItem != null) {
                    ArrayList<Items.Setting> settings = Items.getSettings(controlItem);
                    for (Items.Setting setting : settings) {
                        if (setting.isRequired() && !control.has(setting.getId())) {
                            control = null;
                            break;
                        }
                    }
                }
                mControlJSON = control;
            }
        } catch (JSONException ignored) {
        }
    }
}
 
Example 4
Project: RestaurantApp   File: DeskBasketActivity.java   View Source Code Vote up 6 votes
@Override
public void getDesk(JSONObject result) {

    try {
        JSONArray desks = result.getJSONArray("baskets");
        for (int i=0; i<desks.length(); i++){
            JSONObject desk = (JSONObject) desks.get(i);
            name = desk.getString("name");
            image = desk.getString("image");
            piece = desk.getInt("piece");
            price = desk.getDouble("total");
            basketID = desk.getInt("basketID");

            product = new Product(piece, name, image, price, basketID);
            productList.add(product);

        }

        deskOrderAdapter = new DeskOrderAdapter(this, productList);
        lvBasket.setAdapter(deskOrderAdapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}
 
Example 5
Project: qcloudsms_java   File: SmsSingleSenderResult.java   View Source Code Vote up 6 votes
@Override
public SmsSingleSenderResult parseFromHTTPResponse(HTTPResponse response)
        throws JSONException {

    JSONObject json = parseToJson(response);

    result = json.getInt("result");
    errMsg = json.getString("errmsg");

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

    return this;
}
 
Example 6
Project: wherehowsX   File: TreeFilter.java   View Source Code Vote up 6 votes
public static void getUserFilesTree(JSONObject jsonObject, JSONObject jsonObject2,
                                    Set<Long> fileIdSet) throws Exception {
    if (jsonObject.getInt("folder") == 1) {
        JSONArray jsonArray = jsonObject.getJSONArray("children");
        for (int i=0; i<jsonArray.length(); i++) {
            JSONObject origin = (JSONObject) jsonArray.get(i);
            if (origin.getInt("folder") == 0) {
                if (!fileIdSet.contains(origin.getLong("id"))) continue;
            }

            JSONObject jsonObject1 = new JSONObject();
            // copy..
            copyNode(origin, jsonObject1);
            jsonObject2.getJSONArray("children").put(jsonObject1);
            getUserFilesTree(origin, jsonObject1, fileIdSet);
        }

    }
}
 
Example 7
Project: ripme   File: TapasticRipper.java   View Source Code Vote up 6 votes
@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 8
Project: J-Cord   File: TypingStartEventHandler.java   View Source Code Vote up 5 votes
@Override
public void dispatchEvent(JSONObject json, int sequence) {
    MessageChannel channel = (MessageChannel) identity.getMessageChannel(json.getString("channel_id"));
    User user = (User) identity.getUser(json.getString("user_id"));
    int timeStamp = json.getInt("timestamp");

    dispatchEvent(new TypingStartEvent(identity, sequence, channel, user, timeStamp));
}
 
Example 9
Project: marathonv5   File: JavaServer.java   View Source Code Vote up 5 votes
public void moveto(JSONObject query, JSONObject uriParams, Session session) {
    IJavaElement element = null;
    if (query.has("element")) {
        element = session.findElement(query.getString("element"));
    }
    boolean hasOffset = query.has("xoffset");
    if (hasOffset != query.has("yoffset")) {
        throw new MissingCommandParametersException("Missing x-offset or y-offset. Provide both x and y offsets.", null);
    }
    if (element == null && !hasOffset) {
        throw new MissingCommandParametersException("One of the element or offset is expected.", null);
    }
    int xoffset, yoffset;
    if (hasOffset) {
        xoffset = query.getInt("xoffset");
        yoffset = query.getInt("yoffset");
    } else {
        Point p = element.getMidpoint();
        xoffset = p.x;
        yoffset = p.y;
    }
    if (element == null) {
        if (hasOffset && lastComponenet.element != null) {
            element = lastComponenet.element;
            xoffset += lastComponenet.x;
            yoffset += lastComponenet.y;
        } else {
            element = session.getActiveElement();
        }
    }
    element.moveto(xoffset, yoffset);
    lastComponenet.x = xoffset;
    lastComponenet.y = yoffset;
    lastComponenet.element = element;
}
 
Example 10
Project: vt-support   File: JsonUtil.java   View Source Code Vote up 5 votes
protected static int getIntegerIgnoreErrors(String attribute, JSONObject source,
                                            int defaultValue) {
  if (source.has(attribute)) {
    try {
      return source.getInt(attribute);
    } catch (final JSONException ex) {
      LOG.error("problem getting attribute", ex);
    }
  }
  return defaultValue;
}
 
Example 11
Project: JTradfri   File: TradfriMood.java   View Source Code Vote up 5 votes
/**
 * force a update by a blocking get
 * @return true if it was successful, false if not
 */
public Boolean update() {
	CoapResponse resp = gateway.get("/15005/" + this.group.getGroupID() + "/" + this.moodID);
	
	if(!ResponseCode.isSuccess(resp.getCode())) {
		System.out.println("Mood update for " + this.moodID + "failed!");
		return false;
	}else {
		try {
			JSONObject json = new JSONObject(resp.getResponseText());
			
			//name
			if(json.has("9001")) {
				this.name = json.getString("9001");
			}
			
			//createdAt
			if(json.has("9002")) {
				this.createdAt = json.getInt("9002");
			}
			
			return true;
		}catch(Exception e) {
			System.out.println("Unexpected response: " + e.getMessage()); 
			return false;
		}
	}
}
 
Example 12
Project: OldNews   File: JsonUtils.java   View Source Code Vote up 5 votes
public static Integer getIntFromJson(JSONObject newsItemJson, String key){
    try{
        int value = newsItemJson.getInt(key);
        return value;
    }catch(JSONException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 13
Project: boohee_v5.6   File: AuthAgent.java   View Source Code Vote up 5 votes
public void onComplete(Object obj) {
    Object obj2 = null;
    if (obj != null) {
        JSONObject jSONObject = (JSONObject) obj;
        if (jSONObject != null) {
            String string;
            Object obj3;
            Object obj4;
            String str = "";
            try {
                if (jSONObject.getInt("sendinstall") == 1) {
                    obj2 = 1;
                }
                string = jSONObject.getString("installwording");
                obj3 = obj2;
            } catch (JSONException e) {
                obj4 = null;
                f.d("FeedConfirm", "There is no value for sendinstall.");
                String str2 = str;
                obj3 = obj4;
                string = str2;
            }
            obj4 = URLDecoder.decode(string);
            f.b("TAG", " WORDING = " + obj4 + "xx");
            if (obj3 != null && !TextUtils.isEmpty(obj4)) {
                a(obj4, this.a, obj);
            } else if (this.a != null) {
                this.a.onComplete(obj);
            }
        }
    }
}
 
Example 14
Project: Shadbot   File: ImageCmd.java   View Source Code Vote up 5 votes
private void generateAccessToken() throws JSONException, IOException {
	String url = String.format("https://www.deviantart.com/oauth2/token?client_id=%s&client_secret=%s&grant_type=client_credentials",
			APIKeys.get(APIKey.DEVIANTART_CLIENT_ID),
			APIKeys.get(APIKey.DEVIANTART_API_SECRET));
	JSONObject oauthObj = new JSONObject(NetUtils.getBody(url));
	this.accessToken = oauthObj.getString("access_token");
	this.expiresIn = oauthObj.getInt("expires_in");
	this.lastTokenGeneration = System.currentTimeMillis();
	LogUtils.infof("DeviantArt token generated: %s", this.accessToken);
}
 
Example 15
Project: J-Cord   File: ObjectBuilder.java   View Source Code Vote up 5 votes
public Game buildGame(JSONObject json) {
    JSONObject gameJson = json.getJSONObject("game");
    String name = gameJson.isNull("name") ? null : gameJson.getString("name");
    String url = gameJson.has("type") && gameJson.getInt("type") == IGame.Type.STREAMING.key ?
            gameJson.getString("url") : null;
    return new Game(identity, name, url);
}
 
Example 16
Project: PlayConsoleAndroidAPI   File: AppStoreDetails.java   View Source Code Vote up 5 votes
public Release(JSONObject obj) throws JSONException {
    versionCode = obj.getInt("1");

    changelogs = new ArrayList<>();
    JSONArray changelogsArray = obj.optJSONArray("2");
    if (changelogsArray == null) return;
    for (int i = 0; i < changelogsArray.length(); i++)
        changelogs.add(new LocalizedChangelog(changelogsArray.getJSONObject(i)));
}
 
Example 17
Project: permitlog-android   File: SettingsFragment.java   View Source Code Vote up 4 votes
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    /* This is called when the user picks a new state from the spinner */

    //Get the state the user selected:
    stateName = (String) parent.getItemAtPosition(pos);
    //If this is the default position, set isFillerState:
    isFillerState = (pos == 0);
    try {
        //Get the object containing info about this state:
        JSONObject state = states.getJSONObject(stateName);
        //Get the Boolean value of the "needsForm" key for this state:
        needsForm = state.getBoolean("needsForm");
        //For each type of goal ("total", "day", "night", "weather", "adverse")
        for (String curGoal : DrivingTimes.TIME_TYPES) {
            //Get the required number of hours for this goal in this state
            int curValue = state.getInt(curGoal);

            //This stores whether we want the views to be invisible or visible
            int visibility;
            //If this is the default state
            //or the goal for this state is 0 and it is not the Custom state,
            //hide the views related to this goal
            if(isFillerState || ((curValue == 0) && !stateName.equals("Custom")))
                visibility = View.GONE;
            //Otherwise, make the views for this goal visible
            else visibility = View.VISIBLE;

            Resources res = getResources();
            //Hide or show the inputs and descriptions based on visibility:
            int descViewId = res.getIdentifier(curGoal + "Desc", "id", getContext().getPackageName());
            rootView.findViewById(descViewId).setVisibility(visibility);
            int inputViewId = res.getIdentifier(curGoal + "Input", "id", getContext().getPackageName());
            rootView.findViewById(inputViewId).setVisibility(visibility);
            //Get the textbox for this goal:
            int editViewId = res.getIdentifier(curGoal + "Edit", "id", getContext().getPackageName());
            EditText editView = (EditText) rootView.findViewById(editViewId);
            //If this is the custom state, make the textbox whatever the old goal was:
            if(stateName.equals("Custom") || stateName.equals(oldStateName)) {
                editView.setText(String.valueOf(oldGoals.getTime(curGoal)));
            }
            //Otherwise, make it equal to whatever the goal is for this state:
            else editView.setText(String.valueOf(curValue));
        }
    } catch (JSONException ex) {
        ex.printStackTrace();
        throw new RuntimeException("Inner JSON parsing error");
    }
}
 
Example 18
Project: AndroidPracticalSamples   File: JSONResponseParser.java   View Source Code Vote up 4 votes
public static ResponseException getResponseException(JSONObject response) throws JSONException {
    JSONObject tmp = response.getJSONObject("exception");
    ResponseException exception = new ResponseException(tmp.getInt("code"), tmp.getString("message"));
    return exception;
}
 
Example 19
Project: LoRaWAN-Smart-Parking   File: App.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 20
Project: solo-spring   File: CommentMgmtService.java   View Source Code Vote up 3 votes
/**
 * Article comment count -1 for an article specified by the given article
 * id.
 *
 * @param articleId
 *            the given article id
 * @throws JSONException
 *             json exception
 * @throws RepositoryException
 *             repository exception
 */
private void decArticleCommentCount(final String articleId) throws JSONException, RepositoryException {
	final JSONObject article = articleDao.get(articleId);
	final JSONObject newArticle = new JSONObject(article, JSONObject.getNames(article));
	final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_COUNT);

	newArticle.put(Article.ARTICLE_COMMENT_COUNT, commentCnt - 1);

	articleDao.update(articleId, newArticle);
}