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

The following examples show how to use org.json.JSONObject#optJSONArray() . These examples are extracted from open source projects. 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 Project: catnut   File: UserProcessor.java    License: MIT License 6 votes vote down vote up
@Override
public void asyncProcess(Context context, JSONObject data) throws Exception {
	JSONArray jsonArray = data.optJSONArray(User.MULTIPLE);
	ContentValues[] users = new ContentValues[jsonArray.length()];
	// 可能会包含有这条用户最新的微博存在
	ContentValues[] tweets = null;
	boolean hasTweet = jsonArray.optJSONObject(0).has(Status.SINGLE);
	if (hasTweet) {
		tweets = new ContentValues[users.length];
	}

	for (int i = 0; i < users.length; i++) {
		JSONObject user = jsonArray.optJSONObject(i);
		users[i] = User.METADATA.convert(user);
		if (hasTweet) {
			tweets[i] = Status.METADATA.convert(user.optJSONObject(Status.SINGLE));
		}
	}

	context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
	if (hasTweet) {
		context.getContentResolver().bulkInsert(CatnutProvider.parse(Status.MULTIPLE), tweets);
	}
}
 
Example 2
private void setUpCards(JSONObject payload) {
    JSONArray cards = payload.optJSONArray("cards");
    int size = cards.length();
    cardsContainer.removeAllViews();
    for (int i = 0; i < size; i++) {
        try {
            QiscusCarouselItemView carouselItemView = new QiscusCarouselItemView(cardsContainer.getContext());
            carouselItemView.setPayload(cards.getJSONObject(i));
            carouselItemView.setTitleTextColor(titleTextColor);
            carouselItemView.setDescriptionTextColor(descriptionTextColor);
            carouselItemView.setButtonsTextColor(buttonsTextColor);
            carouselItemView.setButtonsBackgroundColor(buttonsBackgroundColor);
            carouselItemView.setCarouselItemClickListener(carouselItemClickListener);
            carouselItemView.setChatButtonClickListener(chatButtonClickListener);
            carouselItemView.render();
            cardsContainer.addView(carouselItemView);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    cardsContainer.setVisibility(View.VISIBLE);
}
 
Example 3
static ParsedViewDetail convert(JSONObject node) throws JSONException {
  final int left = node.getInt(BaseViewAttributePlugin.KEY_LEFT);
  final int top = node.getInt(BaseViewAttributePlugin.KEY_TOP);
  ParsedViewDetail detail =
      new ParsedViewDetail(
          node.getString(BaseViewAttributePlugin.KEY_CLASS),
          new Rect(
              left,
              top,
              left + node.getInt(BaseViewAttributePlugin.KEY_WIDTH),
              top + node.getInt(BaseViewAttributePlugin.KEY_HEIGHT)));

  JSONArray children = node.optJSONArray(BaseViewHierarchyPlugin.KEY_CHILDREN);
  if (children == null) {
    return detail;
  }

  for (int i = 0; i < children.length(); ++i) {
    detail.children.add(convert(children.getJSONObject(i)));
  }

  return detail;
}
 
Example 4
Source Project: oxAuth   File: ClientUtil.java    License: MIT License 6 votes vote down vote up
public static List<String> extractListByKey(JSONObject jsonObject, String key) {
    final List<String> result = new ArrayList<String>();
    if (jsonObject.has(key)) {
        JSONArray arrayOfValues = jsonObject.optJSONArray(key);
        if (arrayOfValues != null) {
            for (int i = 0; i < arrayOfValues.length(); i++) {
                result.add(arrayOfValues.getString(i));
            }
            return result;
        }
        String listString = jsonObject.optString(key);
        if (StringUtils.isNotBlank(listString)) {
            String[] arrayOfStringValues = listString.split(" ");
            for (String c : arrayOfStringValues) {
                if (StringUtils.isNotBlank(c)) {
                    result.add(c);
                }
            }
        }
    }
    return result;
}
 
Example 5
public void from(Object obj) {
	if (obj != null) {
		if (obj instanceof JSONObject) {
			JSONObject result = (JSONObject) obj;
			this.startTime = result.optString("startTime");
			this.endTime = result.optString("endTime");
			this.timeIncrement = result.optString("timeIncrement");
			JSONArray arrays = result.optJSONArray("results");
			if (arrays != null) {
				int size = arrays.length();
				for (int i = 0; i < size; i++) {
					TransactionStats transactionStats = new TransactionStats();
					transactionStats.from(arrays.getJSONObject(i));
					results.add(transactionStats);
				}
			}
		}
	}
}
 
Example 6
public static List<ConditionActionItem> parseList(JSONArray array) {
    List<ConditionActionItem> list = new ArrayList<>();
    if (array == null || array.length() == 0) {
        return list;
    }
    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.optJSONObject(i);
        ConditionActionItem item = new ConditionActionItem();
        item.name = object.optString("name", "");
        item.modelListJobj = object.optJSONObject("model_list");
        item.mGidJArray = object.optJSONArray("gid");
        item.actionType = object.optInt("type", 0);
        item.mConditionSrc = object.optString("src", "");
        item.mConditionKey = object.optString("key", "");
        list.add(item);
    }
    return list;
}
 
Example 7
private static boolean hasGeo(Message message) {
    if (message == null || message.getInternalData() == null) {
        return false;
    }

    try {
        JSONObject geo = new JSONObject(message.getInternalData());
        JSONArray areas = geo.optJSONArray("geo");
        return areas != null && areas.length() > 0;
    } catch (JSONException e) {
        MobileMessagingLogger.e(e.getMessage());
        return false;
    }
}
 
Example 8
Source Project: letv   File: ParseMenuEntity.java    License: Apache License 2.0 5 votes vote down vote up
public BaseBean Json2Entity(String content) {
    BaseBean oneBean = new BaseBean();
    try {
        JSONObject all = new JSONObject(content);
        oneBean.setMessage(all.optString("message"));
        oneBean.setStatus(all.optString("status"));
        JSONObject resultObj = all.optJSONObject("result");
        if (resultObj != null) {
            JSONArray jsonArray = resultObj.optJSONArray("menuList");
            if (jsonArray != null && jsonArray.length() > 0) {
                oneBean.setBeanList(new ArrayList());
                for (int i = 0; i < jsonArray.length(); i++) {
                    MenuEntity menuObj = new MenuEntity();
                    JSONObject object = jsonArray.optJSONObject(i);
                    menuObj.setUrl(object.optString("url"));
                    menuObj.setTitle(object.optString("title"));
                    menuObj.setIcon(object.optString(SettingsJsonConstants.APP_ICON_KEY));
                    menuObj.setPageFlag(object.optString(Constants.PAGE_FLAG));
                    oneBean.getBeanList().add(menuObj);
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return oneBean;
}
 
Example 9
BookSettings(final JSONObject object) throws JSONException {
    this.persistent = true;
    this.lastChanged = 0;
    this.fileName = object.getString("fileName");
    this.lastUpdated = object.getLong("lastUpdated");

    this.firstPageOffset = object.optInt("firstPageOffset", 1);
    this.currentPage = new PageIndex(object.getJSONObject("currentPage"));
    this.zoom = object.getInt("zoom");
    this.splitPages = object.getBoolean("splitPages");
    this.splitRTL = object.optBoolean("splitRTL", false);
    this.rotation = EnumUtils.getByName(RotationType.class, object, "rotation", RotationType.UNSPECIFIED);
    this.viewMode = EnumUtils.getByName(DocumentViewMode.class, object, "viewMode", DocumentViewMode.VERTICALL_SCROLL);
    this.pageAlign = EnumUtils.getByName(PageAlign.class, object, "pageAlign", PageAlign.AUTO);
    this.animationType = EnumUtils.getByName(PageAnimationType.class, object, "animationType", PageAnimationType.NONE);
    this.cropPages = object.getBoolean("cropPages");
    this.offsetX = (float) object.getDouble("offsetX");
    this.offsetY = (float) object.getDouble("offsetY");
    this.nightMode = object.getBoolean("nightMode");
    this.positiveImagesInNightMode = object.optBoolean("positiveImagesInNightMode", false);
    this.tint = object.optBoolean("tint", false);
    this.tintColor = object.optInt("tintColor", 0);
    this.contrast = object.getInt("contrast");
    this.gamma = object.optInt("gamma", AppPreferences.GAMMA.defValue);
    this.exposure = object.getInt("exposure");
    this.autoLevels = object.getBoolean("autoLevels");
    this.rtl = object.optBoolean("rtl", BookPreferences.BOOK_RTL.getDefaultValue());

    final JSONArray bookmarks = object.optJSONArray("bookmarks");
    if (LengthUtils.isNotEmpty(bookmarks)) {
        for (int i = 0, n = bookmarks.length(); i < n; i++) {
            final JSONObject obj = bookmarks.getJSONObject(i);
            this.bookmarks.add(new Bookmark(obj));
        }
    }

    this.typeSpecific = object.optJSONObject("typeSpecific");

}
 
Example 10
@Override
protected Response<ArrayList<FreshNews>> parseNetworkResponse(NetworkResponse response) {

	try {
		String resultStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
		JSONObject resultObj = new JSONObject(resultStr);
		JSONArray postsArray = resultObj.optJSONArray("posts");
		return Response.success(FreshNews.parse(postsArray), HttpHeaderParser.parseCacheHeaders(response));
	} catch (Exception e) {
		e.printStackTrace();
		return Response.error(new ParseError(e));
	}
}
 
Example 11
Source Project: Simpler   File: MBlog.java    License: Apache License 2.0 5 votes vote down vote up
public static MBlog parse(JSONObject obj) {
    if (obj == null) {
        return null;
    }
    MBlog mBlog = new MBlog();
    mBlog.created_at = obj.optString("created_at", "");
    mBlog.id = obj.optString("id", "");
    mBlog.mid = obj.optString("mid", "");
    mBlog.idstr = obj.optString("idstr", "");
    mBlog.text = obj.optString("text", "");
    mBlog.textLength = obj.optInt("textLength", 0);
    mBlog.source = obj.optString("source", "");
    mBlog.favorited = obj.optBoolean("favorited", false);
    mBlog.user = User.parse(obj.optJSONObject("user"));
    mBlog.retweeted_status = MBlog.parse(obj.optJSONObject("retweeted_status"));
    mBlog.reposts_count = obj.optInt("reposts_count", 0);
    mBlog.comments_count = obj.optInt("comments_count", 0);
    mBlog.attitudes_count = obj.optInt("attitudes_count", 0);
    mBlog.isLongText = obj.optBoolean("isLongText", false);
    mBlog.rid = obj.optString("rid", "");
    mBlog.status = obj.optInt("status", 0);
    mBlog.itemid = obj.optString("itemid", "");
    mBlog.raw_text = obj.optString("raw_text", "");
    mBlog.bid = obj.optString("bid", "");
    
    JSONArray array = obj.optJSONArray("pics");
    if (array != null && array.length() > 0) {
        mBlog.pics = new ArrayList<>(array.length());
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj1 = array.optJSONObject(i);
            mBlog.pics.add(obj1.optString("url").replace("/orj360/", "/thumbnail/"));
        }
    }
    return mBlog;
}
 
Example 12
Source Project: symphonyx   File: TagQueryService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the creator of the specified tag of the given tag id.
 *
 * @param tagId the given tag id
 * @return tag creator, for example,      <pre>
 * {
 *     "tagCreatorThumbnailURL": "",
 *     "tagCreatorThumbnailUpdateTime": 0,
 *     "tagCreatorName": ""
 * }
 * </pre>, returns {@code null} if not found
 *
 * @throws ServiceException service exception
 */
public JSONObject getCreator(final String tagId) throws ServiceException {
    final List<Filter> filters = new ArrayList<Filter>();
    filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId));

    final List<Filter> orFilters = new ArrayList<Filter>();
    orFilters.add(new PropertyFilter(Common.TYPE, FilterOperator.EQUAL, Tag.TAG_TYPE_C_CREATOR));
    orFilters.add(new PropertyFilter(Common.TYPE, FilterOperator.EQUAL, Tag.TAG_TYPE_C_USER_SELF));

    filters.add(new CompositeFilter(CompositeFilterOperator.OR, orFilters));

    final Query query = new Query().setCurrentPageNum(1).setPageSize(1).setPageCount(1).
            setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
            addSort(Keys.OBJECT_ID, SortDirection.ASCENDING);

    try {
        final JSONObject result = userTagRepository.get(query);
        final JSONArray results = result.optJSONArray(Keys.RESULTS);
        final JSONObject creatorTagRelation = results.optJSONObject(0);

        final String creatorId = creatorTagRelation.optString(User.USER + '_' + Keys.OBJECT_ID);

        final JSONObject creator = userRepository.get(creatorId);

        final String creatorEmail = creator.optString(User.USER_EMAIL);
        final String thumbnailURL = avatarQueryService.getAvatarURL(creatorEmail);

        final JSONObject ret = new JSONObject();
        ret.put(Tag.TAG_T_CREATOR_THUMBNAIL_URL, thumbnailURL);
        ret.put(Tag.TAG_T_CREATOR_THUMBNAIL_UPDATE_TIME, creator.optLong(UserExt.USER_UPDATE_TIME));
        ret.put(Tag.TAG_T_CREATOR_NAME, creator.optString(User.USER_NAME));

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets tag creator failed [tagId=" + tagId + "]", e);
        throw new ServiceException(e);
    }
}
 
Example 13
private static void copyAssets(String packageName, String type, JSONObject componentDescriptor) throws IOException, JSONException {
  JSONArray assets = componentDescriptor.optJSONArray("assets");
  if (assets == null) {
    return;
  }

  // Get asset source directory
  String packagePath = packageName.replace('.', File.separatorChar);
  File sourceDir = new File(externalComponentsDirPath + File.separator + ".." + File.separator + ".." + File.separator + "src" + File.separator + packagePath);
  File assetSrcDir = new File(sourceDir, "assets");
  if (!assetSrcDir.exists() || !assetSrcDir.isDirectory()) {
    return;
  }

  // Get asset dest directory
  File destDir = new File(externalComponentsDirPath + File.separator + packageName + File.separator);
  File assetDestDir = new File(destDir, "assets");
  if (assetDestDir.exists() && !deleteRecursively(assetDestDir)) {
    throw new IllegalStateException("Unable to delete the assets directory for the extension.");
  }
  if (!assetDestDir.mkdirs()) {
    throw new IllegalStateException("Unable to create the assets directory for the extension.");
  }

  // Copy assets
  for (int i = 0; i < assets.length(); i++) {
    String asset = assets.getString(i);
    if (!asset.isEmpty()) {
      if (!copyFile(assetSrcDir.getAbsolutePath() + File.separator + asset,
          assetDestDir.getAbsolutePath() + File.separator + asset)) {
        throw new IllegalStateException("Unable to copy asset to destination.");
      }
    }
  }
}
 
Example 14
private DownloadLink getDownloadLink(JSONObject object) throws JSONException {
    String label = object.getString(VERSION_LABEL);
    String singleLink = object.getString(VERSION_LINK);
    JSONArray array = object.optJSONArray(VERSION_LINKS);
    if (array == null) {
        return new DownloadLink(label, new String[]{singleLink});
    }
    int numberOfLinks = array.length();
    String[] multipleLinks = new String[numberOfLinks];
    for (int i = 0; i < numberOfLinks; i++) {
        multipleLinks[i] = array.getString(i);
    }
    return new DownloadLink(label, multipleLinks);
}
 
Example 15
private boolean checkHasErrors(JSONObject response) throws JSONException {
	final JSONArray errorList = response.getJSONArray("error");
	final JSONArray errorFlags = response.optJSONArray("error_flags");
	if (errorFlags != null && errorFlags.length() > 0) {
		lastErrorList = new HashSet<ErrorStatus>();
		for (int i = 0; i < errorFlags.length(); i++) {
			lastErrorList.add(ErrorStatus.valueOf(errorFlags.getString(i)));
		}
	}
	return errorList.length() > 0;
}
 
Example 16
Source Project: BmapLite   File: FavoriteActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void importFav(File file) throws Exception {
    String str = FileUtils.readFileFromSDCard(file);
    JSONObject object = new JSONObject(str);
    boolean isBD09LL = ("bd09ll".equals(object.optString("type_coord")) || "bd09".equals(object.optString("type_coord")));
    if (null != object.optJSONArray("fav") && object.optJSONArray("fav").length() != 0) {
        for (int i = 0; i < object.optJSONArray("fav").length(); i++) {
            MyPoiModel poi = new MyPoiModel(BApp.TYPE_MAP);
            poi.fromJSON(object.optJSONArray("fav").optJSONObject(i));
            if (null != mFavoriteInteracter) {
                LogUtils.debug("isBD09=" + isBD09LL);
                if (isBD09LL) {
                    LogUtils.debug("before=" + poi.getLatitude() + "    " + poi.getLongitude());
                    com.amap.api.maps.CoordinateConverter converter = new com.amap.api.maps.CoordinateConverter(this);
                    converter.from(com.amap.api.maps.CoordinateConverter.CoordType.BAIDU);
                    converter.coord(new com.amap.api.maps.model.LatLng(poi.getLatitude(), poi.getLongitude()));

                    com.amap.api.maps.model.LatLng latLng = new com.amap.api.maps.model.LatLng(converter.convert().latitude, converter.convert().longitude);
                    poi.setLatitude(latLng.latitude);
                    poi.setLongitude(latLng.longitude);
                    LogUtils.debug("after=" + poi.getLatitude() + "    " + poi.getLongitude());
                    mFavoriteInteracter.addFavorite(poi);
                } else {
                    mFavoriteInteracter.addFavorite(poi);
                }
            }
        }
    }

    onMessage("导入成功");
    getData();
}
 
Example 17
private DownloadLink[] getDownloadLinks(JSONObject object) throws JSONException {
    JSONArray array = object.optJSONArray(VERSION_DOWNLOAD_LINKS);
    if (array == null) {
        return new DownloadLink[0];
    }
    int numberOfLinks = array.length();
    DownloadLink[] links = new DownloadLink[numberOfLinks];
    for (int i = 0; i < numberOfLinks; i++) {
        links[i] = getDownloadLink(array.getJSONObject(i));
    }
    return links;
}
 
Example 18
Source Project: kognitivo   File: Utility.java    License: Apache License 2.0 4 votes vote down vote up
public static JSONArray tryGetJSONArrayFromResponse(JSONObject response, String propertyKey) {
    return response != null ? response.optJSONArray(propertyKey) : null;
}
 
Example 19
Source Project: Tangram-Android   File: Card.java    License: MIT License 4 votes vote down vote up
public void parseWith(@NonNull JSONObject data, @NonNull final MVHelper resolver, boolean isParseCell) {
    if (TangramBuilder.isPrintLog()) {
        if (serviceManager == null) {
            throw new RuntimeException("serviceManager is null when parsing card");
        }
    }

    this.extras = data;
    this.type = data.optInt(KEY_TYPE, type);
    this.stringType = data.optString(KEY_TYPE);
    id = data.optString(KEY_ID, id == null ? "" : id);

    loadMore = data.optInt(KEY_LOAD_TYPE, 0) == LOAD_TYPE_LOADMORE;
    //you should alway assign hasMore to indicate there's more data explicitly
    if (data.has(KEY_HAS_MORE)) {
        hasMore = data.optBoolean(KEY_HAS_MORE);
    } else {
        if (data.has(KEY_LOAD_TYPE)) {
            hasMore = data.optInt(KEY_LOAD_TYPE) == LOAD_TYPE_LOADMORE;
        }
    }
    load = data.optString(KEY_API_LOAD, null);
    loadParams = data.optJSONObject(KEY_API_LOAD_PARAMS);
    loaded = data.optBoolean(KEY_LOADED, false);

    maxChildren = data.optInt(KEY_MAX_CHILDREN, maxChildren);
    // parsing header
    if (isParseCell) {
        JSONObject header = data.optJSONObject(KEY_HEADER);
        parseHeaderCell(resolver, header);
    }

    // parsing body
    JSONArray componentArray = data.optJSONArray(KEY_ITEMS);
    if (componentArray != null && isParseCell) {
        final int cellLength = Math.min(componentArray.length(), maxChildren);
        for (int i = 0; i < cellLength; i++) {
            final JSONObject cellData = componentArray.optJSONObject(i);
            createCell(this, resolver, cellData, serviceManager, true);
        }
    }
    // parsing footer
    if (isParseCell) {
        JSONObject footer = data.optJSONObject(KEY_FOOTER);
        parseFooterCell(resolver, footer);
    }

    JSONObject styleJson = data.optJSONObject(KEY_STYLE);

    parseStyle(styleJson);

}
 
Example 20
/**
 * Get a list of all photosets for the specified user.
 * 
 * This method does not require authentication. But to get a Photoset into the list, that contains just private photos, the call needs to be authenticated.
 * 
 * @param userId
 *            The User id
 * @return The Photosets collection
 * @throws IOException
 * @throws FlickrException
 * @throws JSONException
 */
public Photosets getList(String userId) throws IOException, FlickrException, JSONException {
	List<Parameter> parameters = new ArrayList<Parameter>();
	parameters.add(new Parameter("method", METHOD_GET_LIST));

	boolean signed = OAuthUtils.hasSigned();
	if (signed) {
		parameters.add(new Parameter(OAuthInterface.PARAM_OAUTH_CONSUMER_KEY, apiKey));
	} else {
		parameters.add(new Parameter("api_key", apiKey));
	}

	if (userId != null) {
		parameters.add(new Parameter("user_id", userId));
	}

	if (signed) {
		OAuthUtils.addOAuthToken(parameters);
	}

	Response response = signed ? transportAPI.postJSON(sharedSecret, parameters) : transportAPI.get(transportAPI.getPath(), parameters);
	if (response.isError()) {
		throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
	}
	Photosets photosetsObject = new Photosets();
	JSONObject photosetsElement = response.getData().getJSONObject("photosets");
	List<Photoset> photosets = new ArrayList<Photoset>();
	JSONArray photosetElements = photosetsElement.optJSONArray("photoset");
	for (int i = 0; photosetElements != null && i < photosetElements.length(); i++) {
		JSONObject photosetElement = photosetElements.getJSONObject(i);
		Photoset photoset = new Photoset();
		photoset.setId(photosetElement.getString("id"));

		if (photosetElement.has("owner")) {
			User owner = new User();
			owner.setId(photosetElement.getString("owner"));
			photoset.setOwner(owner);
		}

		Photo primaryPhoto = new Photo();
		primaryPhoto.setId(photosetElement.getString("primary"));
		primaryPhoto.setSecret(photosetElement.getString("secret")); // TODO verify that this is the secret for the photo
		primaryPhoto.setServer(photosetElement.getString("server")); // TODO verify that this is the server for the photo
		primaryPhoto.setFarm(photosetElement.getString("farm"));
		photoset.setPrimaryPhoto(primaryPhoto);

		photoset.setSecret(photosetElement.getString("secret"));
		photoset.setServer(photosetElement.getString("server"));
		photoset.setFarm(photosetElement.getString("farm"));
		photoset.setPhotoCount(photosetElement.getString("photos"));

		photoset.setTitle(JSONUtils.getChildValue(photosetElement, "title"));
		photoset.setDescription(JSONUtils.getChildValue(photosetElement, "description"));

		photosets.add(photoset);
	}

	photosetsObject.setPhotosets(photosets);
	return photosetsObject;
}