Java Code Examples for org.json.JSONArray.getJSONObject()

The following are Jave code examples for showing how to use getJSONObject() of the org.json.JSONArray 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: MobileMedia   File: JsonParser.java   View Source Code Vote up 7 votes
public static String parseIatResult(String json) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {
				// 转写结果词,默认使用第一个结果
				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				JSONObject obj = items.getJSONObject(0);
				ret.append(obj.getString("w"));
//				如果需要多候选结果,解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
 
Example 2
Project: Swap   File: Utility.java   View Source Code Vote up 6 votes
/**
 * 解析和处理服务器返回的市级数据
 */
public static boolean handleCityResponse(String response, int provinceId) {
    if (!TextUtils.isEmpty(response)) {
        try {
            JSONArray allCities = new JSONArray(response);
            for (int i = 0; i < allCities.length(); i++) {
                JSONObject cityObject = allCities.getJSONObject(i);
                City city = new City();
                city.setCityName(cityObject.getString("name"));
                city.setCityCode(cityObject.getInt("id"));
                city.setProvinceId(provinceId);
                city.save();
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 3
Project: xqWeather   File: Utility.java   View Source Code Vote up 6 votes
public static boolean handleCityResponse(String response, int provinceId) {
    if (!TextUtils.isEmpty(response)) {
        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                City city = new City();
                city.setId(jsonObject.getInt("id"));
                city.setCityName(jsonObject.getString("name"));
                city.setProvinceId(provinceId);
                city.save();
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}
 
Example 4
Project: J-Cord   File: InviteManager.java   View Source Code Vote up 6 votes
@Override
public List<IInvite> getGuildInvites() {
    if (!guild.getSelfMember().hasPermissions(true, Permission.MANAGE_SERVER)) {
        throw new PermissionException(Permission.ADMINISTRATOR, Permission.MANAGE_SERVER);
    }

    List<IInvite> invites = new ArrayList<>();
    ObjectBuilder builder = new ObjectBuilder((IdentityImpl) getIdentity());
    JSONArray guildInvites = new Requester(getIdentity(), HttpPath.Invite.GET_GUILD_INVITES).request(guild.getId())
            .getAsJSONArray();

    for (int i = 0; i < guildInvites.length(); i++) {
        JSONObject invite = guildInvites.getJSONObject(i);
        invites.add(builder.buildInvite(invite));
    }

    return invites;
}
 
Example 5
Project: Goalie_Android   File: RESTSync.java   View Source Code Vote up 6 votes
private void setupFeeds(JSONArray jsonAll) throws Exception {
    ArrayList<GoalFeed> goalFeedList = new ArrayList<>();

    for (int i = 0; i < jsonAll.length(); i++) {
        JSONObject jsonObj = jsonAll.getJSONObject(i);
        String guid = jsonObj.getString("guid");
        String createdUsername = jsonObj.getString("createdUsername");
        long wager = jsonObj.getLong("wager");
        long upvoteCount = jsonObj.getLong("upvoteCount");

        int goalCompleteResultInt = jsonObj.getInt("goalCompleteResult");
        Goal.GoalCompleteResult goalCompleteResult = Goal.GoalCompleteResult.None;
        if (goalCompleteResultInt < Goal.GoalCompleteResult.values().length)
            goalCompleteResult = Goal.GoalCompleteResult.values()[goalCompleteResultInt];

        GoalFeed goalFeed = new GoalFeed(guid, wager, createdUsername, upvoteCount, goalCompleteResult);
        goalFeedList.add(goalFeed);
    }

    GoalHelper.getInstance().setFeeds(goalFeedList);
}
 
Example 6
Project: marathonv5   File: TestPropertiesInfo.java   View Source Code Vote up 5 votes
private void removeTestIfPresent(JSONObject issue) {
    JSONArray tests = issue.getJSONArray("tests");
    for (int i = 0; i < tests.length(); i++) {
        JSONObject testObj = tests.getJSONObject(i);
        String name = testObj.getString("path");
        if (name.equals(path)) {
            tests.remove(i);
        }
    }
}
 
Example 7
Project: vrops-export   File: Exporter.java   View Source Code Vote up 5 votes
@Override
public JSONObject getParentOf(String id, String parentType) throws JSONException, IOException, HttpException {
	JSONObject json = client.getJson("/suite-api/api/resources/" + id + "/relationships", "relationshipType=PARENT");
	JSONArray rl = json.getJSONArray("resourceList");
	for(int i = 0; i < rl.length(); ++i) {
		JSONObject r = rl.getJSONObject(i);
		
		// If there's more than one we only return the first one.
		//
		if(r.getJSONObject("resourceKey").getString("resourceKindKey").equals(parentType))
			return r;
	}
	return null;
}
 
Example 8
Project: auto-scale-java   File: MesosUtil.java   View Source Code Vote up 5 votes
public static JSONObject getTaskStatistics(String taskName, String host) throws IOException {
    String resp = OKHttpUtil.getInstance().doGet("http://" + host + ":5051/monitor/statistics.json", null,null);
    JSONArray array = new JSONArray(resp);
    for (int i = 0; i < array.length(); i++) {
        JSONObject jsonObj = array.getJSONObject(i);
        String executorId = jsonObj.getString("executor_id");
        if (executorId.equals(taskName)) {
            return jsonObj.getJSONObject("statistics");
        }
    }
    return null;
}
 
Example 9
Project: appinventor-extensions   File: ExternalComponentGenerator.java   View Source Code Vote up 5 votes
private static Map<String, JSONObject> buildInfoAsMap(JSONArray buildInfos) throws JSONException {
  Map<String, JSONObject> result = new HashMap<String, JSONObject>();
  for (int i = 0; i < buildInfos.length(); i++) {
    JSONObject componentBuildInfo = buildInfos.getJSONObject(i);
    result.put(componentBuildInfo.getString("type"), componentBuildInfo);
  }
  return result;
}
 
Example 10
Project: marathonv5   File: FavouriteHistoryStage.java   View Source Code Vote up 5 votes
private JSONObject removeAndGetTest(String section) {
    JSONArray history = TestRunnerHistory.getInstance().getHistory(section);
    for (int i = 0; i < history.length(); i++) {
        JSONObject test = history.getJSONObject(i);
        JSONObject selectedItem = historyView.getSelectionModel().getSelectedItem();
        if (test.getString("name").equals(selectedItem.getString("name"))) {
            historyView.getItems().remove(historyView.getSelectionModel().getSelectedItem());
            history.remove(i);
            return test;
        }
    }
    return null;
}
 
Example 11
Project: alfresco-remote-api   File: SiteServiceTest.java   View Source Code Vote up 5 votes
public void testGetMemberships() throws Exception
{
    // Create a site
    String shortName  = GUID.generate();
    createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);
    
    // Check the memberships
    Response response = sendRequest(new GetRequest(URL_SITES + "/" + shortName + URL_MEMBERSHIPS), 200);
    JSONArray result = new JSONArray(response.getContentAsString());        
    assertNotNull(result);
    assertEquals(1, result.length());
    JSONObject membership = result.getJSONObject(0);
    assertEquals(SiteModel.SITE_MANAGER, membership.get("role"));
    assertEquals(USER_ONE, membership.getJSONObject("authority").get("userName"));        
}
 
Example 12
Project: J-Cord   File: MessageHistory.java   View Source Code Vote up 5 votes
/**
 * Get a list of all pinned messages of a channel.
 *
 * @return the list of messages, list size without limits.
 */
public List<IMessage> getPinnedMessages() {
    JSONArray pins = new Requester(identity, HttpPath.Channel.GET_PINNED_MESSAGES)
            .request(channel.getId()).getAsJSONArray();

    ObjectBuilder builder = new ObjectBuilder(identity);
    List<IMessage> pinnedMessages = new ArrayList<>();
    for (int i = 0; i < pins.length(); i++) {
        JSONObject msg = pins.getJSONObject(i);
        Message message = builder.buildMessage(msg);
        pinnedMessages.add(message);
    }
    history.cacheAll(pinnedMessages.toArray(new IMessage[pinnedMessages.size()]));
    return pinnedMessages;
}
 
Example 13
Project: android-chessclock   File: TimeControlParser.java   View Source Code Vote up 5 votes
/**
 * Get the stored TimeControl list from shared preferences.
 *
 * @return TimeControl list.
 */
public static ArrayList<TimeControl> restoreTimeControlsList(Context context) {

    Log.i(TAG, "Looking for stored time controls");

    SharedPreferences sp = getSharedPreferences(context);
    String jsonString = sp.getString(TIME_CONTROLS_PREF_FIELD_NAME, null);

    if (jsonString == null) {
        Log.w(TAG, "Not able to read the preference");
        return null;
    }

    ArrayList<TimeControl> timeControls = new ArrayList<TimeControl>();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray timeControlsJSONArray = json.getJSONArray("timecontrols");
        for (int i = 0; i < timeControlsJSONArray.length(); i++) {
            JSONObject timeControlJSON = timeControlsJSONArray.getJSONObject(i);

            JSONObject timeIncrementJSONOBject = timeControlJSON.getJSONObject("timeincrement");
            JSONArray timeControlStagesJSON = timeControlJSON.getJSONArray("stages");

            String name = timeControlJSON.getString("name");
            Stage[] stages = getStages(timeControlStagesJSON);
            TimeIncrement timeIncrement = getTimeIncrement(timeIncrementJSONOBject);

            TimeControl timeControl = new TimeControl(name, stages, timeIncrement);
            timeControls.add(timeControl);
        }

    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
        return null;
    }

    Log.i(TAG, "Retrieving " + timeControls.size() + " time controls.");
    return timeControls;
}
 
Example 14
Project: alerta-fraude   File: ContactManager.java   View Source Code Vote up 5 votes
private void search(JSONArray args) throws JSONException
{
    final JSONArray filter = args.getJSONArray(0);
    final JSONObject options = args.get(1) == null ? null : args.getJSONObject(1);
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            JSONArray res = contactAccessor.search(filter, options);
            callbackContext.success(res);
        }
    });
}
 
Example 15
Project: siiMobilityAppKit   File: Calendar.java   View Source Code Vote up 5 votes
private void deleteEvent(JSONArray args) {
  if (args.length() == 0) {
    System.err.println("Exception: No Arguments passed");
    return;
  }

  // note that if the dev didn't call requestWritePermission before calling this method and calendarPermissionGranted returns false,
  // the app will ask permission and this method needs to be invoked again (done for backward compat).
  if (!calendarPermissionGranted(Manifest.permission.WRITE_CALENDAR)) {
    requestWritePermission(PERMISSION_REQCODE_DELETE_EVENT);
    return;
  }

  try {
    final JSONObject jsonFilter = args.getJSONObject(0);

    cordova.getThreadPool().execute(new Runnable() {
      @Override
      public void run() {

        boolean deleteResult = getCalendarAccessor().deleteEvent(
                null,
                jsonFilter.optLong("startTime"),
                jsonFilter.optLong("endTime"),
                getPossibleNullString("title", jsonFilter),
                getPossibleNullString("location", jsonFilter));

        callback.sendPluginResult(new PluginResult(PluginResult.Status.OK, deleteResult));
      }
    });
  } catch (JSONException e) {
    System.err.println("Exception: " + e.getMessage());
    callback.error(e.getMessage());
  }
}
 
Example 16
Project: atlas   File: BundleListingUtil.java   View Source Code Vote up 4 votes
public static LinkedHashMap<String,BundleListing.BundleInfo> parseArray(String listingStr) throws Exception{
    LinkedHashMap<String,BundleListing.BundleInfo> infos= new LinkedHashMap<>();
    JSONArray array = new JSONArray(listingStr);
    for(int x=0; x<array.length(); x++){
        JSONObject object = array.getJSONObject(x);
        BundleListing.BundleInfo info = new BundleListing.BundleInfo();
        info.name = object.optString("name");
        info.pkgName = object.optString("pkgName");
        info.applicationName = object.optString("applicationName");
        info.version = object.optString("version");
        info.desc = object.optString("desc");
        info.url = object.optString("url");
        info.md5 = object.optString("md5");
        String uniqueTag = object.optString("unique_tag");
        if(TextUtils.isEmpty(uniqueTag)){
            throw new IOException("uniqueTag is empty");
        }
        info.unique_tag = object.optString("unique_tag");
        if (object.has("isInternal")) {
            info.isInternal = object.optBoolean("isInternal");
        }

        JSONArray dependency = object.optJSONArray("dependency");
        if(dependency!=null && dependency.length()>0){
            List<String> dependencyList = new ArrayList<String>();
            for(int i=0; i<dependency.length(); i++){
                dependencyList.add(dependency.getString(i));
            }
            info.setDependency(dependencyList);
        }

        JSONArray activities = object.optJSONArray("activities");
        if(activities!=null && activities.length()>0){
            HashMap<String,Boolean> activitiesList = new HashMap<String,Boolean>();
            for(int i=0; i<activities.length(); i++){
                activitiesList.put(activities.getString(i),Boolean.FALSE);
            }
            info.activities = activitiesList;
        }

        JSONArray services = object.optJSONArray("services");
        if(services!=null && services.length()>0){
            HashMap<String,Boolean> servicesList = new HashMap<String,Boolean>();
            for(int i=0; i<services.length(); i++){
                servicesList.put(services.getString(i),Boolean.FALSE);
            }
            info.services = servicesList;
        }

        JSONArray receivers = object.optJSONArray("receivers");
        if(receivers!=null && receivers.length()>0){
            HashMap<String,Boolean> receiversList = new HashMap<String,Boolean>();
            for(int i=0; i<receivers.length(); i++){
                receiversList.put(receivers.getString(i),Boolean.FALSE);
            }
            info.receivers = receiversList;
        }

        JSONArray contentProviders = object.optJSONArray("contentProviders");
        if(contentProviders!=null && contentProviders.length()>0){
            HashMap<String,Boolean> contentProvidersList = new HashMap<String,Boolean>();
            for(int i=0; i<contentProviders.length(); i++){
                contentProvidersList.put(contentProviders.getString(i),Boolean.FALSE);
            }
            info.contentProviders = contentProvidersList;
        }

        infos.put(info.getPkgName(),info);

    }
    return infos.size()>0 ? infos : null;
}
 
Example 17
Project: alfresco-repository   File: SolrJSONResultSet.java   View Source Code Vote up 4 votes
protected List<GenericFacetResponse> buildPivot(JSONObject facet_pivot, String pivotName, List<RangeParameters> rangeParameters) throws JSONException
{
    if (!facet_pivot.has(pivotName)) return Collections.emptyList();

    JSONArray pivots = facet_pivot.getJSONArray(pivotName);
    Map<String,List<GenericBucket>> pivotBuckets = new HashMap<>(pivots.length());
    List<GenericFacetResponse> facetResponses = new ArrayList<>();
    for(int i = 0; i < pivots.length(); i++)
    {
        JSONObject piv = pivots.getJSONObject(i);
        Set<Metric> metrics = new HashSet<>(1);
        List<GenericFacetResponse> nested = new ArrayList<>();
        String field = piv.getString("field");
        String value = piv.getString("value");
        if (piv.has("stats"))
        {
            JSONObject stats = piv.getJSONObject("stats");
            Map<String, Map<String, Object>> pivotStats = buildStats(stats);
            pivotStats.forEach((pKey, pVal) -> {
               metrics.addAll(getMetrics(pVal));
            });
        }

        Integer count = Integer.valueOf(piv.getInt("count"));
        metrics.add(new SimpleMetric(METRIC_TYPE.count,count));
        nested.addAll(buildPivot(piv, "pivot", rangeParameters));

        if (piv.has("ranges"))
        {
            JSONObject ranges = piv.getJSONObject("ranges");
            Map<String, List<Map<String, String>>> builtRanges = buildRanges(ranges);
            List<GenericFacetResponse> rangefacets = RangeResultMapper.getGenericFacetsForRanges(builtRanges,rangeParameters);
            nested.addAll(rangefacets);
        }

        GenericBucket buck = new GenericBucket(value, field+":\""+value+"\"", null, metrics, nested);
        List<GenericBucket> listBucks = pivotBuckets.containsKey(field)?pivotBuckets.get(field):new ArrayList<>();
        listBucks.add(buck);
        pivotBuckets.put(field, listBucks);
    }

    for (Map.Entry<String, List<GenericBucket>> entry : pivotBuckets.entrySet()) {
        facetResponses.add(new GenericFacetResponse(FACET_TYPE.pivot,entry.getKey(),entry.getValue()));
    }

    if (!facetResponses.isEmpty()) return facetResponses;

    return Collections.emptyList();
}
 
Example 18
Project: mdw-demo   File: SlackRequest.java   View Source Code Vote up 4 votes
public SlackRequest(JSONObject json) {
    if (json.has("name"))
        this.name = json.getString("name");
    if (json.has("value"))
        this.value = json.getString("value");
    if (json.has("callback_id"))
        this.callbackId = json.getString("callback_id");
    if (json.has("trigger_id"))
        this.triggerId = json.getString("trigger_id");
    if (json.has("channel")) {
        JSONObject channelObj = json.getJSONObject("channel");
        if (channelObj.has("name"))
            this.channel = channelObj.getString("name");
    }
    if (json.has("team")) {
        JSONObject teamObj = json.getJSONObject("team");
        if (teamObj.has("domain"))
            this.team = teamObj.getString("domain");
    }
    if (json.has("type"))
        this.type = json.getString("type");
    if (json.has("user")) {
        JSONObject userObj = json.getJSONObject("user");
        if (userObj.has("name"))
            this.user = userObj.getString("name");
    }
    if (json.has("message_ts"))
        this.messageTs = json.getString("message_ts");
    if (json.has("action_ts"))
        this.actionTs = json.getString("action_ts");
    if (json.has("actions")) {
        this.actions = new ArrayList<>();
        JSONArray actionsArr = json.getJSONArray("actions");
        for (int i = 0; i < actionsArr.length(); i++) {
            JSONObject actionObj = actionsArr.getJSONObject(i);
            if (actionObj.has("name"))
                this.actions.add(actionObj.getString("name"));
            if (actionObj.has("value")) {
                // value is used for user selection
                this.value = actionObj.getString("value");
            }
            else if (actionObj.has("selected_options")) {
                JSONArray selOptionsArr = actionObj.getJSONArray("selected_options");
                if (selOptionsArr.length() != 0) {
                    // only a single selection for now
                    JSONObject selOptionObj = selOptionsArr.getJSONObject(0);
                    if (selOptionObj.has("value"))
                        this.value = selOptionObj.getString("value");
                }
            }
        }
    }
    if (json.has("response_url"))
        this.responseUrl = json.getString("response_url");
        
}
 
Example 19
Project: Nearby   File: Supporter.java   View Source Code Vote up 3 votes
public static ArrayList<Supporter> getSrtSupporterList(String data){

        ArrayList<Supporter> list = new ArrayList<>();

        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray results = jObject.getJSONArray("result");
            String countTemp = (String)jObject.get("num_result");
            int count = Integer.parseInt(countTemp);

            for ( int i = 0; i < count; ++i ) {
                JSONObject temp = results.getJSONObject(i);

                Supporter supporter = new Supporter();
                supporter.convertSrt(temp);

                list.add(supporter);

            }

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

        return list;

    }
 
Example 20
Project: Nearby   File: PatientWeight.java   View Source Code Vote up 3 votes
public static ArrayList<PatientWeight> getPatientWeightList(String data){

        ArrayList<PatientWeight> list = new ArrayList<>();

        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray results = jObject.getJSONArray("result");
            String countTemp = (String)jObject.get("num_result");
            int count = Integer.parseInt(countTemp);

            for ( int i = 0; i < count; ++i ) {
                JSONObject temp = results.getJSONObject(i);

                PatientWeight pw = new PatientWeight();
                pw.convert(temp);

                list.add(pw);

            }

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

        return list;

    }