Java Code Examples for org.json.JSONArray#length()

The following examples show how to use org.json.JSONArray#length() . 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: BroadcastEventData.java    From Easer with GNU General Public License v3.0 10 votes vote down vote up
public void parse(@NonNull String data, @NonNull PluginDataFormat format, int version) throws IllegalStorageDataException {
    intentData = new ReceiverSideIntentData();
    switch (format) {
        default:
            try {
                JSONObject jsonObject = new JSONObject(data);
                JSONArray jsonArray_action = jsonObject.getJSONArray(K_ACTION);
                for (int i = 0; i < jsonArray_action.length(); i++) {
                    intentData.action.add(jsonArray_action.getString(i));
                }
                JSONArray jsonArray_category = jsonObject.getJSONArray(K_CATEGORY);
                for (int i = 0; i < jsonArray_category.length(); i++) {
                    intentData.category.add(jsonArray_category.getString(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                throw new IllegalStorageDataException(e);
            }
    }
}
 
Example 2
Source File: JsonCfgConverter.java    From AndroidLinkup with GNU General Public License v2.0 8 votes vote down vote up
/**
 * 将Json配置转化为游戏配置
 * 
 * @param jsonCfg
 *            Json配置
 * @return 游戏模式配置
 */
public static List<ModeCfg> toCfg(JSONObject jsonCfg) {
    modeIndex = 0;
    rankIndex = 0;
    levelIndex = 0;
    List<ModeCfg> modeCfgs = new ArrayList<ModeCfg>();
    try {
        toGlobalCfg(jsonCfg.getJSONObject("globalcfg"));
        JSONArray jsonModes = jsonCfg.getJSONArray("modeCfgs");
        for (int i = 0; i < jsonModes.length(); i++) {
            ModeCfg modeCfg = toModeCfg(jsonModes.getJSONObject(i));
            if (modeCfg != null) {
                modeCfgs.add(modeCfg);
            }
        }
        return modeCfgs;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: RedPacketParser.java    From letv with Apache License 2.0 6 votes vote down vote up
public RedPacketBean parser(JSONObject data) throws Exception {
    parsePollingController(data);
    RedPacketBean bean = new RedPacketBean();
    if (has(data, "blockContent")) {
        JSONArray jsonArray = data.getJSONArray("blockContent");
        if (!(jsonArray == null || jsonArray.length() == 0)) {
            RedPacketSdkManager.getInstance().setRedPacketList(jsonArray);
        }
        bean = parserRedPacketList(jsonArray);
        bean.type = RedPacketBean.TYPE_REDPACKET;
    }
    this.mPollingResult.hasRedPacket = RedPacketSdkManager.getInstance().hasRedPacket(bean);
    if (this.mCallback != null) {
        this.mCallback.onReceivePollingResult(this.mPollingResult);
        this.mCallback = null;
    }
    LogInfo.log("RedPacketParser", "parser + Network is ok,parse polling result is finish");
    return bean;
}
 
Example 4
Source File: CompositeDataSourceConfiguration.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Load relations from a jsonobject. The structure of the json object is the same of the relation file
 * 
 * @param relationshipsConfJSON
 * @return
 */
private List<IModelRelationshipDescriptor> loadMyRelationships(JSONObject relationshipsConfJSON) {
	List<IModelRelationshipDescriptor> relationship;

	relationship = new ArrayList<IModelRelationshipDescriptor>();

	try {
		JSONArray relationshipsJSON = relationshipsConfJSON.optJSONArray("relationships");
		if (relationshipsJSON != null) {
			for (int i = 0; i < relationshipsJSON.length(); i++) {
				JSONObject relationshipJSON = relationshipsJSON.getJSONObject(i);
				relationship.add(new ModelRelationshipDescriptor(relationshipJSON));
			}
		}

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

	return relationship;
}
 
Example 5
Source File: RealCDXExtractorOutput.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
private String extractHTMLMetaRefresh(String origUrl, MetaData m) {
	JSONArray metas = JSONUtils.extractArray(m, "Envelope.Payload-Metadata.HTTP-Response-Metadata.HTML-Metadata.Head.Metas");
	if(metas != null) {
		int count = metas.length();
		for(int i = 0; i < count; i++) {
			JSONObject meta = metas.optJSONObject(i);
			if(meta != null) {
				String name = scanHeadersLC(meta, "http-equiv", null);
				if(name != null) {
					if(name.toLowerCase().equals("refresh")) {
						// alright - some robot instructions:
						String content = scanHeadersLC(meta, "content", null);
						if(content != null) {
							String fragment = parseMetaRefreshContent(content);
							if(fragment != null) {
								return fragment;
							}
						}
					}
				}
			}
		}
	}
	return "-";
}
 
Example 6
Source File: TestRunner.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private State findState(String path, JSONArray tests) {
    for (int i = 0; i < tests.length(); i++) {
        JSONObject test = tests.getJSONObject(i);
        if (test.has("tests")) {
            State s = findState(path, test.getJSONArray("tests"));
            if (s != null) {
                return s;
            }
        } else {
            String oPath = test.getString("path");
            if (oPath.equals(path)) {
                return State.valueOf(test.getString("state"));
            }
        }
    }
    return null;
}
 
Example 7
Source File: FormViewerQueryTransformer.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void applyStaticOpenFilters(Query query) throws Exception {
	logger.debug("IN");
	JSONArray staticOpenFilters = template.optJSONArray(QbeJSONTemplateParser.STATIC_OPEN_FILTERS);
	if (staticOpenFilters != null && staticOpenFilters.length() > 0) {
		for (int i = 0; i < staticOpenFilters.length(); i++) {
			JSONObject filter = (JSONObject) staticOpenFilters.get(i);
			String id = filter.getString(QbeJSONTemplateParser.ID);
			List<String> values = formViewerState.getOpenFilterValues(id);
			if (values.size() > 0) {
				String operator = filter.getString("operator");
				if (operator.equals(CriteriaConstants.EQUALS_TO)) {
					operator = CriteriaConstants.IN;
				}
				WhereField.Operand leftOperand = new WhereField.Operand(new String[] {filter.getString("field")}, null, AbstractStatement.OPERAND_TYPE_SIMPLE_FIELD, null, null);
				WhereField.Operand rightOperand = new WhereField.Operand(values.toArray(new String[]{}), null, AbstractStatement.OPERAND_TYPE_STATIC, null, null);
				query.addWhereField(id, null, false, leftOperand, operator, rightOperand, "AND");
				updateWhereClauseStructure(query, filter.getString(QbeJSONTemplateParser.ID), "AND");
			}
		}
	}
	logger.debug("OUT");
}
 
Example 8
Source File: BackupContainer.java    From Android-PreferencesManager with Apache License 2.0 6 votes vote down vote up
public static BackupContainer fromJSON(JSONArray filesArray) {
    BackupContainer container = new BackupContainer();
    for (int i = 0; i < filesArray.length(); i++) {
        JSONObject obj = filesArray.optJSONObject(i);
        if (obj != null) {
            String file = obj.optString(KEY_FILE);
            JSONArray backupsArray = obj.optJSONArray(KEY_BACKUPS);
            if (backupsArray != null) {
                for (int j = 0; j < backupsArray.length(); j++) {
                    String _backup = backupsArray.optString(j);
                    if (!TextUtils.isEmpty(_backup)) {
                        container.put(file, _backup);
                    }
                }
            }
        }
    }
    return container;
}
 
Example 9
Source File: AcFunDanmakuParser.java    From BlueBoard with Apache License 2.0 5 votes vote down vote up
private void onJsonArrayParse(JSONArray danmakuArray) {
    if (danmakuArray != null || danmakuArray.length() > 0) {

        for (int i = 0; i < danmakuArray.length(); i++) {
            try {
                onJsonObjectParse(danmakuArray.getJSONObject(i));
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}
 
Example 10
Source File: StatusProcessor.java    From catnut with MIT License 5 votes vote down vote up
@Override
public void asyncProcess(Context context, JSONObject data) throws Exception {
	JSONArray commentsArray = data.optJSONArray(Status.COMMENTS);
	ContentValues[] comments = new ContentValues[commentsArray.length()];
	ContentValues[] users = new ContentValues[comments.length];
	JSONObject json;
	for (int i = 0; i < comments.length; i++) {
		json = commentsArray.optJSONObject(i);
		comments[i] = Comment.METADATA.convert(json);
		users[i] = User.METADATA.convert(json.optJSONObject(User.SINGLE));
	}
	context.getContentResolver().bulkInsert(CatnutProvider.parse(Comment.MULTIPLE), comments);
	context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
}
 
Example 11
Source File: NetEaseUserAdaptor.java    From YiBo with Apache License 2.0 5 votes vote down vote up
/**
 * 从JSON字符串创建User对象列表
 *
 * @param jsonString
 *            JSON字符串
 * @return User对象列表
 * @throws LibException
 */
public static PagableList<User> createPagableUserList(String jsonString) throws LibException {
	try {
		if ("[]".equals(jsonString) || "{}".equals(jsonString)) {
			return new PagableList<User>(0, 0, 0);
		}
		JSONObject json = new JSONObject(jsonString);
		JSONArray jsonList = json.getJSONArray("users");
		long nextCursor = 0L;
		long previousCursor = 0L;
		if (!json.isNull("next_cursor")) {
			nextCursor = ParseUtil.getLong("next_cursor", json);
			previousCursor = ParseUtil.getLong("previous_cursor", json);
		}

		if (nextCursor == -1) {
			//网易的cursor分页,没有下一页时next_cursor为-1,这里做一下修改,统一为0
			nextCursor = 0;
		}

		int size = jsonList.length();
		PagableList<User> userList = new PagableList<User>(size, previousCursor, nextCursor);
		for (int i = 0; i < size; i++) {
			userList.add(createUser(jsonList.getJSONObject(i)));
		}
		return userList;
	} catch (JSONException e) {
		throw new LibException(LibResultCode.JSON_PARSE_ERROR);
	}
}
 
Example 12
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String giveConsent(JSONArray args){
    try {
        this.log("giveConsent", args);
        String consent = null;
        List<String> features = new ArrayList<>();
        for (int i = 0; i < args.length(); i++) {
            consent = args.getString(i);
            if (consent.equals("sessions")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.sessions});
            }
            if (consent.equals("events")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.events});
            }
            if (consent.equals("views")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.views});
            }
            if (consent.equals("location")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.location});
            }
            if (consent.equals("crashes")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.crashes});
            }
            if (consent.equals("attribution")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.attribution});
            }
            if (consent.equals("users")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.users});
            }
            if (consent.equals("push")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.push});
            }
            if (consent.equals("starRating")) {
                Countly.sharedInstance().consent().giveConsent(new String[]{Countly.CountlyFeatureNames.starRating});
            }
        }
        return "giveConsent: Success";
    }catch (JSONException jsonException){
        return jsonException.toString();
    }
}
 
Example 13
Source File: SourceMapConsumerV3.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private String[] getJavaStringArray(JSONArray array) throws JSONException {
  int len = array.length();
  String[] result = new String[len];
  for(int i = 0; i < len; i++) {
    result[i] = array.getString(i);
  }
  return result;
}
 
Example 14
Source File: ArchiveRepository.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an archive with the specified time.
 *
 * @param time the specified time
 * @return archive, returns {@code null} if not found
 * @throws RepositoryException repository exception
 */
public JSONObject getArchive(final long time) throws RepositoryException {
    final String archiveDate = DateFormatUtils.format(time, "yyyyMMdd");

    final Query query = new Query().setCurrentPageNum(1).setPageCount(1).
            setFilter(new PropertyFilter(Archive.ARCHIVE_DATE, FilterOperator.EQUAL, archiveDate));
    final JSONObject result = get(query);
    final JSONArray data = result.optJSONArray(Keys.RESULTS);

    if (data.length() < 1) {
        return null;
    }

    return data.optJSONObject(0);
}
 
Example 15
Source File: AccountCollectionSerde.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a json object representing a collection of accounts.
 * @param json the {@link JSONObject} to deserialize.
 * @return a {@link Collection} of {@link Account}s.
 */
public static Collection<Account> fromJson(JSONObject json) {
  JSONArray accountArray = json.optJSONArray(ACCOUNTS_KEY);
  if (accountArray == null) {
    return Collections.emptyList();
  } else {
    Collection<Account> accounts = new ArrayList<>();
    for (int i = 0; i < accountArray.length(); i++) {
      JSONObject accountJson = accountArray.getJSONObject(i);
      accounts.add(Account.fromJson(accountJson));
    }
    return accounts;
  }
}
 
Example 16
Source File: JSONUtils.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public static List<String> toStringList(JSONArray array) throws JSONException {
    if(array == null) {
        return null;
    }
    else {
        List<String> list = new ArrayList<String>();

        for (int i = 0; i < array.length(); i++) {
            list.add(array.get(i).toString());
        }

        return list;
    }
}
 
Example 17
Source File: ArticleQueryService.java    From symphonyx with Apache License 2.0 4 votes vote down vote up
/**
 * Gets news (articles tags contains "B3log Announcement").
 *
 * @param currentPageNum the specified page number
 * @param pageSize the specified page size
 * @return articles, return an empty list if not found
 * @throws ServiceException service exception
 */
public List<JSONObject> getNews(final int currentPageNum, final int pageSize) throws ServiceException {
    JSONObject tag;

    try {
        tag = tagRepository.getByTitle("B3log Announcement");
        if (null == tag) {
            return Collections.emptyList();
        }

        Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
                setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)))
                .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);

        JSONObject result = tagArticleRepository.get(query);
        final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);

        final Set<String> articleIds = new HashSet<String>();
        for (int i = 0; i < tagArticleRelations.length(); i++) {
            articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
        }

        final JSONObject sa = userQueryService.getSA();

        final List<Filter> subFilters = new ArrayList<Filter>();
        subFilters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
        subFilters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_EMAIL, FilterOperator.EQUAL, sa.optString(User.USER_EMAIL)));
        query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, subFilters))
                .addProjection(Article.ARTICLE_TITLE, String.class).addProjection(Article.ARTICLE_PERMALINK, String.class)
                .addProjection(Article.ARTICLE_CREATE_TIME, Long.class).addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING);
        result = articleRepository.get(query);

        final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
        for (final JSONObject article : ret) {
            article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
        }

        return ret;
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets news failed", e);
        throw new ServiceException(e);
    }
}
 
Example 18
Source File: Facts.java    From Crimson with Apache License 2.0 3 votes vote down vote up
private void parseFacts(JSONObject response) {

        try {

            List<AllFacts> list = new ArrayList<>();
            AllFacts allFacts;

            JSONArray factsArray =  response.getJSONArray("all_facts");

            for (int i=0;i<factsArray.length();i++){

                JSONObject factObject = factsArray.getJSONObject(i);

                String fact = factObject.getString("facts");
                String source = factObject.getString("source");

                allFacts = new AllFacts();

                allFacts.setFact(fact);
                allFacts.setSource(source);

                list.add(allFacts);

            }

            showFacts(list);



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

    }
 
Example 19
Source File: ManageDataSetsForREST.java    From Knowage-Server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * @param parametersMap
 * @param parsListJSON
 * @return
 */
private boolean hasDuplicates(HashMap<String, String> parametersMap, JSONArray parsListJSON) {
	return parsListJSON.length() > parametersMap.keySet().size();
}
 
Example 20
Source File: LengthUtils.java    From document-viewer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Safely calculates an array length.
 *
 * @param arr
 *          array
 * @return real array length or <code>0</code> if reference is <code>null</code>
 */
public static int length(final JSONArray arr) {
  return arr != null ? arr.length() : 0;
}