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

The following examples show how to use org.json.JSONObject#optInt() . 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: ServerInfo.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public void update(JSONObject json) {
    // TODO, this might asking for trouble, just assuming certain fields, it should BLOW UP

    fee_base          = json.optInt(     "fee_base",          fee_base);
    txn_count         = json.optInt(     "txn_count",          txn_count);
    fee_ref           = json.optInt(     "fee_ref",           fee_ref);
    reserve_base      = json.optInt(     "reserve_base",      reserve_base);
    reserve_inc       = json.optInt(     "reserve_inc",       reserve_inc);
    load_base         = json.optInt(     "load_base",         load_base);
    load_factor       = json.optInt(     "load_factor",       load_factor);
    ledger_time       = json.optLong(     "ledger_time",       ledger_time);
    ledger_index      = json.optLong(    "ledger_index",      ledger_index);
    ledger_hash       = json.optString(  "ledger_hash",       ledger_hash);
    validated_ledgers = json.optString(  "validated_ledgers", validated_ledgers);

    random            = json.optString(  "random",            random);
    server_status     = json.optString(  "server_status",     server_status);

    updated = true;
}
 
Example 2
Source File: UserList.java    From Simpler with Apache License 2.0 6 votes vote down vote up
public static UserList parse(JSONObject jsonObject) {
    UserList userList = new UserList();
    userList.next_cursor = jsonObject.optInt("next_cursor", 0);
    userList.previous_cursor = jsonObject.optInt("previous_cursor", 0);
    userList.total_number = jsonObject.optLong("total_number", 0L);
    JSONArray array = jsonObject.optJSONArray("users");
    if (array != null && array.length() > 0) {
        userList.users = new ArrayList<>(array.length());
        User user = null;
        for (int i = 0; i < array.length(); i++) {
            user = User.parse(array.optJSONObject(i));
            if (user != null) {
                userList.users.add(user);
            }
        }
    }
    return userList;
}
 
Example 3
Source File: News.java    From opencdk-appwidget with Apache License 2.0 6 votes vote down vote up
public static News toObject(String jsonString) {
	News news = null;
	try {
		JSONObject json = new JSONObject(jsonString);

		String title = json.optString("title");
		String date = json.optString("date");
		int newsMark = json.optInt("newsMark", 0);

		news = new News();
		news.setTitle(title);
		news.setDate(date);
		news.setNewsMark(newsMark);
	} catch (JSONException e) {
		// e.printStackTrace();
	}

	return news;
}
 
Example 4
Source File: CardList.java    From Simpler with Apache License 2.0 6 votes vote down vote up
public static CardList parse(JSONObject obj) {
    if (obj == null) {
        return null;
    }
    CardList cardList = new CardList();
    cardList.cardlistInfo = CardListInfo.parse(obj.optJSONObject("cardlistInfo"));

    JSONArray array = obj.optJSONArray("cards");
    if (array != null && array.length() > 0) {
        cardList.cards = new ArrayList<>(array.length());
        for (int i = 0; i < array.length(); i++) {
            Card card = Card.parse(array.optJSONObject(i));
            if (card != null) {
                cardList.cards.add(card);
            }
        }
    }
    cardList.ok = obj.optInt("ok", 0);
    cardList.seeLevel = obj.optInt("seeLevel", 0);
    cardList.showAppTips = obj.optInt("showAppTips", 0);
    cardList.scheme = obj.optString("scheme", "");
    return cardList;
}
 
Example 5
Source File: QuestionContentFragment.java    From ONE-Unofficial with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataOk(String url, String data) {
    switch (url) {
        case Api.URL_QUESTION:
            Question question = JsonUtil.getEntity(data, Question.class);
            refreshUI(question);
            if (question != null) {
                Paper.book().write(Constants.TAG_QUESTION + curDate, question);
            }
            QuestionFragment.getInstance().pager.onRefreshComplete();
            break;
        case Api.URL_LIKE_OR_CANCLELIKE:
            try {
                JSONObject jsonObject = new JSONObject(data);
                int likeCount = jsonObject.optInt("strPraisednumber");
                //若实际的喜欢数量与LikeView自增的结果值不同,更新显示最新的数量
                if (likeCount != lvQuestion.getLikeCount()) {
                    lvQuestion.setText(likeCount + "");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
    }
}
 
Example 6
Source File: GridCard.java    From Tangram-Android with MIT License 6 votes vote down vote up
@Override
public void parseWith(JSONObject data) {
    super.parseWith(data);

    if (data != null) {
        column = data.optInt(KEY_COLUMN, 0);

        autoExpand = data.optBoolean(KEY_AUTO_EXPAND, false);

        JSONArray jsonCols = data.optJSONArray(KEY_COLS);
        if (jsonCols != null) {
            cols = new float[jsonCols.length()];
            for (int i = 0; i < cols.length; i++) {
                cols[i] = (float) jsonCols.optDouble(i, 0);
            }
        } else {
            cols = new float[0];
        }

        hGap = Style.parseSize(data.optString(KEY_H_GAP), 0);
        vGap = Style.parseSize(data.optString(KEY_V_GAP), 0);
    }
}
 
Example 7
Source File: FlightFeatureConfiguration.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
public ValueConfiguration(JSONObject json) {
    if (json != null) {
        JSONArray values = json.optJSONArray("preset_values");

        presets = new ArrayList<>();
        for (int i = 0; i < values.length(); i++) {
            presets.add(values.optDouble(i));
        }

        int defaultIndex = json.optInt("default_value_index");
        setDefaultValue(presets.get(defaultIndex));

        setConversionFactor(json.optDouble("conversion_factor", 1));

        setUnit(optString(json, "unit"));
    }
}
 
Example 8
Source File: Element.java    From SikuliNG with MIT License 6 votes vote down vote up
private void init(JSONObject jElement) {
  if (jElement.has("type") && "ELEMENT".equals(jElement.getString("type"))) {
    x = jElement.optInt("x", 0);
    y = jElement.optInt("y", 0);
    h = jElement.optInt("h", -1);
    w = jElement.optInt("w", -1);
    score = jElement.optDouble("score", -1);
    if (!jElement.isNull("name")) {
      name = jElement.getString("name");
    }
    if (!jElement.isNull("lastMatch")) {
      lastMatch = new Element();
      JSONObject jLastMatch = jElement.getJSONObject("lastMatch");
      lastMatch.x = jLastMatch.optInt("x", 0);
      lastMatch.y = jLastMatch.optInt("y", 0);
      lastMatch.h = jLastMatch.optInt("h", -1);
      lastMatch.w = jLastMatch.optInt("w", -1);
      lastMatch.score = jLastMatch.optDouble("score", 0);
    }
  } else {
    log.error("new (JSONObject jElement): not super-type ELEMENT: %s", jElement);
  }
}
 
Example 9
Source File: Country.java    From country-picker-android with Apache License 2.0 5 votes vote down vote up
public static Country fromJson(String json){
    if(TextUtils.isEmpty(json)) return null;
    try {
        JSONObject jo = new JSONObject(json);
        return new Country(jo.optInt("code") ,jo.optString("name"), jo.optString("locale"), jo.optInt("flag"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 10
Source File: EventManager.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(int action, String resultJson) throws RemoteException {
	switch (action) {
		case RemoteService.EVENT_GET_FEEDBACK_MSG:
			FeedbackAgent.onGetFeedbackListener(true, resultJson);
			break;
		case RemoteService.EVENT_UPDATE_APK:	
			updateManager.isUpdateListener(resultJson);
			break;
		case RemoteService.EVENT_DOWNLOAD_APK:
			try {						
				JSONObject object = new JSONObject(resultJson);
				int progress = object.optInt("progress");
				String msg = object.optString("msg");
				if(progress == 0){
					updateManager.downloadStart();//OnDownloadStart();
				}else if(progress == 100){
					updateManager.downloadEnd(UpdateStatus.DOWNLOAD_COMPLETE_SUCCESS, msg);//OnDownloadEnd(UpdateStatus.DOWNLOAD_COMPLETE_SUCCESS, resultJson);
				}else{
					updateManager.downloadUpdate(progress);//OnDownloadUpdate(progress);
				}
			} catch (Exception e) {
				EventManager.onError(context, e.getMessage());
				Ln.e("EventManager == ", "AIDLCallback == EVENT_DOWNLOAD_APK", e);
			}
		case RemoteService.EVENT_EXIT_APK:
			String exitDate = resultJson;
			dbHelper.setAppExitDate(exitDate);
			break;
		default:
			break;
	}
}
 
Example 11
Source File: RingerModeConditionData.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
RingerModeConditionData(@NonNull String data, @NonNull PluginDataFormat format, int version) throws IllegalStorageDataException {
    switch (format) {
        default:
            try {
                JSONObject jsonObject = new JSONObject(data);
                this.ringerMode = jsonObject.optInt(T_ringerMode);
                this.ringerLevel = jsonObject.optInt(T_ringerLevel);
                this.compareMode = jsonObject.optInt(T_compareMode);
            } catch (JSONException e) {
                e.printStackTrace();
                throw new IllegalStorageDataException(e);
            }
    }
}
 
Example 12
Source File: VKApiPlace.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a Place instance from JSONObject.
 */
public VKApiPlace parse(JSONObject from) {
    id = from.optInt("id");
    title = from.optString("title");
    latitude = from.optDouble("latitude");
    longitude = from.optDouble("longitude");
    created = from.optLong("created");
    checkins = from.optInt("checkins");
    updated = from.optLong("updated");
    country_id = from.optInt("country");
    city_id = from.optInt("city");
    address = from.optString("address");
    return this;
}
 
Example 13
Source File: PhotoSizeImpl.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
private PhotoSizeImpl(JSONObject jsonObject) {

        this.file_id = jsonObject.getString("file_id");
        this.width = jsonObject.optInt("width");
        this.height = jsonObject.optInt("height");
        this.file_size = jsonObject.optInt("file_size");
    }
 
Example 14
Source File: KanboardActivity.java    From Kandroid with GNU General Public License v3.0 5 votes vote down vote up
public KanboardActivity(JSONObject json) {
    Title = json.optString("event_title");
    Content = json.optString("event_content");
    Creator = json.optString("author");
    CreatorUserName = json.optString("author_username");
    CreatorId = json.optInt("creator_id");
    Id = json.optInt("id");
    ProjectId = json.optInt("project_id");
    TaskId = json.optInt("task_id");
    DateCreation = new Date(json.optLong("date_creation") * 1000);
}
 
Example 15
Source File: CTABVariant.java    From clevertap-android-sdk with MIT License 5 votes vote down vote up
public static CTABVariant initWithJSON(JSONObject json) {
    try {
        String experimentId = json.optString("exp_id", "0");
        String variantId = json.optString("var_id", "0");
        int version = json.optInt("version", 0);
        final JSONArray actions = json.optJSONArray("actions");
        final JSONArray vars = json.optJSONArray("vars");
        CTABVariant variant = new CTABVariant(experimentId, variantId, version, actions, vars);
        Logger.v("Created CTABVariant:  " + variant.toString());
        return variant;
    } catch (Throwable t) {
        Logger.v("Error creating variant", t);
        return null;
    }
}
 
Example 16
Source File: AlbumsPluginImpl.java    From socialauth with MIT License 5 votes vote down vote up
private List<Photo> getAlbumPhotos(final String id) throws Exception {
	Response response = providerSupport.api(
			String.format(ALBUM_PHOTOS_URL, id), MethodType.GET.toString(),
			null, null, null);
	String respStr = response.getResponseBodyAsString(Constants.ENCODING);
	LOG.info("Getting Photos of Album :: " + id);
	JSONObject resp = new JSONObject(respStr);
	JSONArray data = resp.getJSONArray("data");
	LOG.debug("Photos count : " + data.length());
	List<Photo> photos = new ArrayList<Photo>();
	for (int i = 0; i < data.length(); i++) {
		Photo photo = new Photo();
		JSONObject obj = data.getJSONObject(i);
		photo.setId(obj.optString("id", null));
		photo.setTitle(obj.optString("name", null));
		photo.setLink(obj.optString("link", null));
		photo.setThumbImage(obj.optString("picture", null));
		JSONArray images = obj.getJSONArray("images");
		for (int k = 0; k < images.length(); k++) {
			JSONObject img = images.getJSONObject(k);
			int ht = 0;
			int wt = 0;
			if (img.has("height")) {
				ht = img.optInt("height");
			}
			if (img.has("width")) {
				wt = img.optInt("width");
			}
			if (ht == 600 || wt == 600) {
				photo.setLargeImage(img.optString("source"));
			} else if (ht == 480 || wt == 480) {
				photo.setMediumImage(img.optString("source"));
			} else if (ht == 320 || wt == 320) {
				photo.setSmallImage(img.optString("source"));
			}
		}
		photos.add(photo);
	}
	return photos;
}
 
Example 17
Source File: OrderListSerialContext.java    From bizsocket with Apache License 2.0 5 votes vote down vote up
@Override
public Packet processPacket(RequestQueue requestQueue, Packet packet) {
    if (orderListPacket != null && orderIdArr != null && orderTypeMap.size() == orderIdArr.length) {
        try {
            JSONObject obj = new JSONObject(orderListPacket.getContent());
            JSONArray resultArr = obj.optJSONArray("result");
            for (int i = 0;i < resultArr.length();i++) {
                JSONObject order = resultArr.optJSONObject(i);
                int orderId = order.optInt("orderId");

                JSONObject orderType = new JSONObject(((SamplePacket)orderTypeMap.get(orderId)).getContent());
                order.put("orderType",orderType.optInt("ordertype",0));
                order.put("orderTypeRes",orderType);
            }

            SamplePacket samplePacket = (SamplePacket) packet;
            samplePacket.setCommand(orderListPacket.getCommand());
            samplePacket.setContent(obj.toString());

            System.out.println("合并订单列表和类型: " + samplePacket.getContent());
            return samplePacket;
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 18
Source File: NumberParser.java    From react-native-navigation with MIT License 4 votes vote down vote up
public static Number parse(JSONObject json, String number) {
    return json.has(number) ? new Number(json.optInt(number)) : new NullNumber();
}
 
Example 19
Source File: UserProcessor.java    From symphonyx with Apache License 2.0 4 votes vote down vote up
/**
 * Shows user home follower users page.
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @param userName the specified user name
 * @throws Exception exception
 */
@RequestProcessing(value = "/member/{userName}/followers", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = StopwatchEndAdvice.class)
public void showHomeFollowers(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response, final String userName) throws Exception {
    final JSONObject user = (JSONObject) request.getAttribute(User.USER);

    request.setAttribute(Keys.TEMAPLTE_DIR_NAME, Symphonys.get("skinDirName"));
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("/home/followers.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    filler.fillHeaderAndFooter(request, response, dataModel);

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);

    final int pageSize = Symphonys.getInt("userHomeFollowersCnt");
    final int windowSize = Symphonys.getInt("userHomeFollowersWindowSize");

    fillHomeUser(dataModel, user);

    final String followingId = user.optString(Keys.OBJECT_ID);
    dataModel.put(Follow.FOLLOWING_ID, followingId);

    final JSONObject followerUsersResult = followQueryService.getFollowerUsers(followingId, pageNum, pageSize);
    final List<JSONObject> followerUsers = (List) followerUsersResult.opt(Keys.RESULTS);
    dataModel.put(Common.USER_HOME_FOLLOWER_USERS, followerUsers);
    avatarQueryService.fillUserAvatarURL(user);

    final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
    if (isLoggedIn) {
        final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
        final String followerId = currentUser.optString(Keys.OBJECT_ID);

        final boolean isFollowing = followQueryService.isFollowing(followerId, followingId);
        dataModel.put(Common.IS_FOLLOWING, isFollowing);

        for (final JSONObject followerUser : followerUsers) {
            final String homeUserFollowerUserId = followerUser.optString(Keys.OBJECT_ID);

            followerUser.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowerUserId));
        }
    }

    user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));

    final int followerUserCnt = followerUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
    final int pageCount = (int) Math.ceil((double) followerUserCnt / (double) pageSize);

    final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
    if (!pageNums.isEmpty()) {
        dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
        dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
    }

    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
}
 
Example 20
Source File: LottieImageAsset.java    From atlas with Apache License 2.0 4 votes vote down vote up
static LottieImageAsset newInstance(JSONObject imageJson) {
  return new LottieImageAsset(imageJson.optInt("w"), imageJson.optInt("h"), imageJson.optString("id"),
      imageJson.optString("p"));
}