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

The following examples show how to use org.json.JSONObject#getJSONArray() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Utils   File: JSONGetter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get String array from jsonObject
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li>
 * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li>
 * <li>return string array</li>
 * </ul>
 */
public static String[] getStringArray(JSONObject jsonObject, String key, String[] defaultValue) {
    if (jsonObject == null || TextUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        JSONArray statusArray = jsonObject.getJSONArray(key);
        if (statusArray != null) {
            String[] value = new String[statusArray.length()];
            for (int i = 0; i < statusArray.length(); i++) {
                value[i] = statusArray.getString(i);
            }
            return value;
        }
    } catch (JSONException e) {
        if (sPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
    return defaultValue;
}
 
Example 2
Source Project: ripme   File: MangadexRipper.java    License: MIT License 6 votes vote down vote up
@Override
protected List<String> getURLsFromJSON(JSONObject json) {
    List<String> assetURLs = new ArrayList<>();
    JSONArray currentObject;

    String chapterHash = json.getString("hash");
    // Server is the cdn hosting the images.
    String server = json.getString("server");

    for (int i = 0; i < json.getJSONArray("page_array").length(); i++) {
        currentObject = json.getJSONArray("page_array");

        assetURLs.add(getImageUrl(chapterHash, currentObject.getString(i), server));
    }

    return assetURLs;
}
 
Example 3
Source Project: ripme   File: MastodonRipper.java    License: MIT License 6 votes vote down vote up
@Override
public List<String> getURLsFromPage(Document doc) {
    List<String> result = new ArrayList<String>();
    for (Element el : doc.select("[data-component=\"MediaGallery\"]")) {
        String props = el.attr("data-props");
        JSONObject obj = new JSONObject(props);
        JSONArray arr = obj.getJSONArray("media");
        for (int i = 0; i < arr.length(); i++) {
            String url = arr.getJSONObject(i).getString("url");
            result.add(url);
            String id = arr.getJSONObject(i).getString("id");
            itemIDs.put(url, id);
        }
    }
    return result;
}
 
Example 4
Source Project: myapplication   File: JsonHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static List<News> parseJsonToList(String json) throws JSONException {
    JSONObject newsContent = new JSONObject(json);
    JSONArray newsArray = newsContent.getJSONArray("stories");
    List<News> newsList = new ArrayList<News>();
    for (int i = 0; i < newsArray.length(); i++) {
        JSONObject newsInJson = newsArray.getJSONObject(i);
        int id = newsInJson.optInt("id");
        String title = newsInJson.optString("title");
        String image = "";
        if (newsInJson.has("images")) {
            image = (String) newsInJson.getJSONArray("images").get(0);

        }
        News news = new News(id, title, image);
        newsList.add(news);
    }
    return newsList;
}
 
Example 5
private static Data createFormFromJSONObject(JSONObject o) {
    Data data = new Data();
    JSONArray names = o.names();
    for (int i = 0; i < names.length(); ++i) {
        try {
            String name = names.getString(i);
            JSONArray jsonValues = o.getJSONArray(name);
            ArrayList<String> values = new ArrayList<>(jsonValues.length());
            for (int j = 0; j < jsonValues.length(); ++j) {
                values.add(jsonValues.getString(j));
            }
            data.put(name, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return data;
}
 
Example 6
Source Project: oxAuth   File: GluuConfigurationClient.java    License: MIT License 6 votes vote down vote up
private Map<String, Set<String>> mapJsonToScopeToClaimsMapping(JSONObject jsonObject) {
    Map<String, Set<String>> scopeToClaimsMapping = new HashMap<String, Set<String>>();
    Iterator<?> keys = jsonObject.keys();
    while (keys.hasNext()) {
        try {
            String scope = (String) keys.next();

            scopeToClaimsMapping.put(scope, new HashSet<String>());

            JSONArray jsonArray = jsonObject.getJSONArray(scope);
            for (int i = 0; i < jsonArray.length(); i++)
                scopeToClaimsMapping.get(scope).add(jsonArray.getString(i));
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
    return scopeToClaimsMapping;
}
 
Example 7
public void testGetRuleTypes() throws Exception
{
    Response response = sendRequest(new GetRequest(URL_RULETYPES), 200);
    JSONObject result = new JSONObject(response.getContentAsString());

    assertNotNull(result);

    assertTrue(result.has("data"));

    JSONArray data = result.getJSONArray("data");

    for (int i = 0; i < data.length(); i++)
    {
        JSONObject ruleType = data.getJSONObject(i);

        assertTrue(ruleType.has("name"));
        assertTrue(ruleType.has("displayLabel"));
        assertTrue(ruleType.has("url"));
    }
}
 
Example 8
Source Project: iview-android-tv   File: TvShowListApi.java    License: MIT License 6 votes vote down vote up
private List<EpisodeBaseModel> getEpisodesFromList(JSONArray groups, boolean addToCollection) {
    List<EpisodeBaseModel> titles = new ArrayList<>();
    for (int i = 0, k = groups.length(); i < k; i++) {
        try {
            if (groups.get(i) instanceof JSONObject) {
                JSONObject group = groups.getJSONObject(i);
                List<EpisodeBaseModel> episodes = new ArrayList<>();
                if (group.has("episodes") && group.get("episodes") instanceof JSONArray) {
                    JSONArray data = group.getJSONArray("episodes");
                    for (int j = 0, m = data.length(); j < m; j++) {
                        episodes.add(EpisodeModel.create(data.getJSONObject(j)));
                    }
                }
                if (episodes.size() > 0 && addToCollection && group.has("title") && group.get("title") instanceof String) {
                    collections.put(group.getString("title"), episodes);
                }
                titles.addAll(episodes);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return titles;
}
 
Example 9
Source Project: archivo   File: Tivo.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a new Tivo object from a JSON String.
 *
 * @param json String containing the Tivo object in JSON
 * @param mak  Media access key to use for the resulting Tivo
 * @return A new Tivo object
 * @throws IllegalArgumentException on invalid address
 */
public static Tivo fromJSON(final String json, final String mak) throws IllegalArgumentException {
    JSONObject jo = new JSONObject(json);
    String name = jo.getString(JSON_NAME);
    String tsn = jo.getString(JSON_TSN);
    int port = jo.getInt(JSON_PORT);
    JSONArray jsonAddresses = jo.getJSONArray(JSON_ADDRESSES);
    Set<InetAddress> addresses = new HashSet<>();
    Base64.Decoder decoder = Base64.getDecoder();
    for (int i = 0; i < jsonAddresses.length(); i++) {
        try {
            addresses.add(InetAddress.getByAddress(decoder.decode(jsonAddresses.getString(i))));
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("TiVo address in invalid: " + e.getLocalizedMessage());
        }
    }

    return new Builder().name(name).tsn(tsn).port(port).addresses(addresses).mak(mak).build();
}
 
Example 10
private int parseTrainingSamples() {
    Jedis redis = DataStore.getJedisConnection();
    int newSampleCount = 0;

    String line = null;
    long consumptionStart = new Date().getTime();
    try {
        while ((line = getInfoMessage(redis)) != null
                && new Date().getTime() - consumptionStart < timeThreshold) {

            logger.info("A training sample has arrived");

            // Parse notification containing event id and attribute ids
            JSONObject obj = new JSONObject(line);
            int crisisID = obj.getInt("crisis_id");
            JSONArray attrArr = obj.getJSONArray("attributes");
            int[] attributeIDs = new int[attrArr.length()];
            for (int i = 0; i < attrArr.length(); i++) {
                attributeIDs[i] = attrArr.getInt(i);
            }
            increment(crisisID, attributeIDs, 1);
            if (obj.has("force_retrain") && obj.getBoolean("force_retrain")) {
                if (!forceRetrains.containsKey(crisisID)) {
                    forceRetrains.put(crisisID, new ArrayList<Integer>());
                }
                for (int attributeID : attributeIDs) {
                    forceRetrains.get(crisisID).add(attributeID);
                }
            }

            newSampleCount++;
        }
    } catch (Exception e) {
        logger.error("Exception while processing training sample message queue", e);
    } finally {
        DataStore.close(redis);
    }

    return newSampleCount;
}
 
Example 11
private void addGroupMembers(MethodCall call, final Result result) {
  HashMap<String, Object> map = call.arguments();

  long groupId;
  JSONArray usernameJsonArr;
  String appKey;
  List<String> usernameList = new ArrayList<String>();

  try {
    JSONObject params = new JSONObject(map);

    groupId = Long.parseLong(params.getString("id"));
    appKey = params.has("appKey") ? params.getString("appKey") : JmessageFlutterPlugin.appKey;
    usernameJsonArr = params.getJSONArray("usernameArray");

    for (int i = 0; i < usernameJsonArr.length(); i++) {
      usernameList.add(usernameJsonArr.getString(i));
    }
  } catch (JSONException e) {
    e.printStackTrace();
    handleResult(ERR_CODE_PARAMETER, ERR_MSG_PARAMETER, result);
    return;
  }

  JMessageClient.addGroupMembers(groupId, appKey, usernameList, new BasicCallback() {
    @Override
    public void gotResult(int status, String desc) {
      handleResult(status, desc, result);
    }
  });
}
 
Example 12
/**
 * Constructor used to build a new UnitTypeList with a JSON object. This is
 * used to recall saved Unit Type Arrays that might have different visibility,
 * order, or unit customizations from the user.
 *
 * @param json Object to load JSON from
 * @throws JSONException
 */
public UnitTypeList(Resources resources, JSONObject json) throws JSONException {
	this(resources); // initialize unit array

	JSONArray jUnitTypeArray = json.getJSONArray(JSON_UNIT_TYPE_MAP);

	//if we added another UnitType and total count is different than previous
	// just use default
	if (jUnitTypeArray.length() == mUnitTypes.size()){
		//Load in user settings to already assembled UnitType array
		int i = 0;
		for (String key : mUnitTypes.keySet()) {
			mUnitTypes.get(key).loadJSON(jUnitTypeArray.getJSONObject(i));
			i++;
		}

		//load out the array or keys that define the desired order
		JSONArray jUnitOrderArray = json.getJSONArray(JSON_UNIT_TYPE_ORDER);
		ArrayList<String> temp = new ArrayList<>();
		for (int k = 0; k < jUnitOrderArray.length(); k++) {
			temp.add(jUnitOrderArray.getString(k));
		}
		mOrderedUnitKeys = temp;

		//grab the current key
		mCurrentKey = json.getString(JSON_UNIT_TYPE);
	}
}
 
Example 13
private Map<String, Object> buildModel(WebScriptRequest req) throws JSONException, IOException
{
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);

    Content content = req.getContent();
    if(content == null)
    {
        throw new WebScriptException("Failed to convert request to String");
    }
    JSONObject o = new JSONObject(content.getContent());
    JSONArray jsonModels = o.getJSONArray("models");
    Map<QName, Long> models = new HashMap<QName, Long>(jsonModels.length());
    for(int i = 0; i < jsonModels.length(); i++)
    {
        JSONObject jsonModel = jsonModels.getJSONObject(i);
        models.put(QName.createQName(jsonModel.getString("name")), jsonModel.getLong("checksum"));
    }

    List<AlfrescoModelDiff> diffs = solrTrackingComponent.getModelDiffs(models);
    model.put("diffs", diffs);

    if (logger.isDebugEnabled())
    {
        logger.debug("Result: \n\tRequest: " + req + "\n\tModel: " + model);
    }
    
    return model;
}
 
Example 14
Source Project: monolog-android   File: JsonUtils.java    License: MIT License 5 votes vote down vote up
public static JSONArray getArray(String key, JSONObject jsonObject)
		throws Exception {
	JSONArray res = new JSONArray();
	if (jsonObject.has(key)) {
		try {
			res = jsonObject.getJSONArray(key);
		} finally {
			return res;
		}
	}
	return null;
}
 
Example 15
Source Project: m2x-android   File: DeviceService.java    License: MIT License 5 votes vote down vote up
@Override
List<Stream> parseResponse(JSONObject jsonObject) throws JSONException {
    JSONArray streams = jsonObject.getJSONArray("streams");
    List<Stream> streamsList = new ArrayList<>(streams.length());
    for (int i = 0; i < streams.length(); ++i) {
        streamsList.add(Stream.fromJsonObject(streams.getJSONObject(i)));
    }
    return streamsList;
}
 
Example 16
Source Project: socialauth   File: FeedPluginImpl.java    License: MIT License 4 votes vote down vote up
@Override
public List<Feed> getFeeds() throws Exception {
	List<Feed> list = new ArrayList<Feed>();
	try {
		Response response = providerSupport.api(FEED_URL);
		String respStr = response
				.getResponseBodyAsString(Constants.ENCODING);
		JSONObject resp = new JSONObject(respStr);
		JSONArray data = resp.getJSONArray("data");
		LOG.debug("Feeds count : " + data.length());
		for (int i = 0; i < data.length(); i++) {
			Feed feed = new Feed();
			JSONObject obj = data.getJSONObject(i);
			if (obj.has("from")) {
				JSONObject fobj = obj.getJSONObject("from");
				feed.setFrom(fobj.optString("name", null));
				feed.setId(fobj.optString("id", null));
			}
			if (obj.has("message")) {
				feed.setMessage(obj.optString("message", null));
			} else if (obj.has("story")) {
				feed.setMessage(obj.optString("story", null));
			} else if (obj.has("name")) {
				feed.setMessage(obj.optString("name", null));
			} else if (obj.has("caption")) {
				feed.setMessage(obj.optString("caption", null));
			} else if (obj.has("description")) {
				feed.setMessage(obj.getString("description"));
			} else if (obj.has("picture")) {
				feed.setMessage(obj.optString("picture", null));
			}

			String createdTime = obj.optString("created_time", null);
			if (createdTime != null) {
				feed.setCreatedAt(dateFormat.parse(createdTime));
			}
			list.add(feed);
		}
	} catch (Exception e) {
		throw new SocialAuthException("Error while getting Feeds from "
				+ FEED_URL, e);
	}
	return list;
}
 
Example 17
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

	View view = inflater.inflate(R.layout.fr_json_request, container,false);

	carDataList = new ArrayList<Map<String, String>>();

	lvCar = (ListView) view.findViewById(R.id.lv_car);
	adapter = new SimpleAdapter(getActivity(), carDataList, R.layout.fr_json_request_list_item, keys, ids);
	lvCar.setAdapter(adapter);

	// 发起请求

	JsonObjectRequest request = new JsonObjectRequest(StringUtil.preUrl(Constants.DEFAULT_JSON_REQUEST_URL), null,
			new Listener<JSONObject>() {

				@Override
				public void onResponse(JSONObject response) {
					try {
						if (!response.has("result")) {
							return;
						}

						JSONObject result = response.getJSONObject("result");

						if (!result.has("fctlist")) {
							return;
						}

						JSONArray factoryArray = result.getJSONArray("fctlist");

						if (factoryArray.length() == 0) {
							return;
						}

						JSONObject factory = factoryArray.getJSONObject(0);

						if (!factory.has("serieslist")) {
							return;
						}

						JSONArray seriesArray = factory.getJSONArray("serieslist");

						carDataList.clear();

						for (int i = 0; i < seriesArray.length(); i++) {
							JSONObject series = seriesArray.getJSONObject(i);
							Map<String, String> seriesMap = new HashMap<String, String>();

							seriesMap.put("name", series.getString("name"));
							seriesMap.put("level", "级别:"+series.getString("levelname"));
							seriesMap.put("price", "价格:"+series.getString("price"));

							carDataList.add(seriesMap);

						}
						
						adapter.notifyDataSetChanged();

					} catch (Exception e) {
						ToastUtil.showToast(getActivity(), getResources().getString(R.string.request_fail_text));
					}

				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError arg0) {
					ToastUtil.showToast(getActivity(), getResources().getString(R.string.request_fail_text));
				}
			});
	// 请求加上Tag,用于取消请求
	request.setTag(this);

	VolleyUtil.getQueue(getActivity()).add(request);

	return view;
}
 
Example 18
@Override
public void onJsonReceive(String path, JSONObject js) {
    if (qaOverlay == null || !isAdded()) {
        jsonQueueNames.add(path);
        jsonQueueObjects.add(js);
        return;
    }

    if (path.equals(CommonIdentifiers.P2W_RESPOND_CARD)) {
        try {

            hideButtons();
            unblockControls();
            qHtml = js.getString("q");
            aHtml = js.getString("a");

            setQA(false);

            noteID = js.getLong("note_id");
            cardOrd = js.getInt("card_ord");
            nextReviewTimes = js.getJSONArray("b");
            numButtons = nextReviewTimes.length();
            hideLoadingSpinner();
            showQuestion();

            setQA(true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (path.equals(CommonIdentifiers.P2W_NO_MORE_CARDS)) {
        blockControls();
        hideLoadingSpinner();
        mTextView.setText("No more Cards");
    } else if (path.equals(W2W_REMOVE_SCREEN_LOCK)) {
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Log.d("ReviewFragment", "removing screen lock");
    } else if (path.equals(W2W_RELOAD_HTML_FOR_MEDIA)) {
        setQA(true);
        Log.d("ReviewFragment", "reloading Html for media");
    }
}
 
Example 19
private List<String> getTenants() {
	logger.debug("IN");
	List<String> tenants = new ArrayList<>();

	try {
		OAuth2Client oauth2Client = new OAuth2Client();

		Properties config = OAuth2Config.getInstance().getConfig();

		// Retrieve the admin's token for REST services authentication
		String token = oauth2Client.getAdminToken();

		HttpClient httpClient = oauth2Client.getHttpClient();

		// Get roles of the application (specified in the
		// oauth2.config.properties)
		String url = config.getProperty("REST_BASE_URL") + "users/" + config.getProperty("ADMIN_ID") + "/projects";
		GetMethod httpget = new GetMethod(url);
		httpget.addRequestHeader("X-Auth-Token", token);

		int statusCode = httpClient.executeMethod(httpget);
		byte[] response = httpget.getResponseBody();
		if (statusCode != HttpStatus.SC_OK) {
			logger.error("Error while getting organizations from OAuth2 provider: server returned statusCode = " + statusCode);
			LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });
			throw new SpagoBIRuntimeException("Error while getting organizations from OAuth2 provider: server returned statusCode = " + statusCode);
		}

		String responseStr = new String(response);
		LogMF.debug(logger, "Server response is:\n{0}", responseStr);
		JSONObject jsonObject = new JSONObject(responseStr);
		JSONArray organizationsList = jsonObject.getJSONArray("projects");

		for (int i = 0; i < organizationsList.length(); i++) {
			if (!organizationsList.getJSONObject(i).has("is_default")) {
				String organizationId = organizationsList.getJSONObject(i).getString("id");
				String organizationName = getTenantName(organizationId);

				tenants.add(organizationName);

			}
		}

		return tenants;
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to obtain tenants' informations from OAuth2 provider", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 20
Source Project: Fatigue-Detection   File: FilterFactory.java    License: MIT License 4 votes vote down vote up
public static MakeupData parseMakeUpInfo(String paramString, JSONObject paramJSONObject)
        throws IOException, JSONException {
    MakeupData locala = new MakeupData();
    locala.ep = paramJSONObject.getInt("resloadtype");
    locala.name = paramJSONObject.getString("foldername");
    locala.cN = paramJSONObject.getInt("maxcount");
    JSONArray localJSONArray1 = paramJSONObject.getJSONArray("triangles");
    locala.cN = Math.min(localJSONArray1.length(), locala.cN);

    locala.eo = new ArrayList();
    for (int i = 0; i < locala.cN; i++) {
        MakeupData.a locala1 = new MakeupData.a();
        JSONObject localJSONObject = localJSONArray1.getJSONObject(i);

        locala1.eq = localJSONObject.getString("res");
        JSONArray localJSONArray2 = localJSONObject.getJSONArray("vertexIndexes");
        locala1.er = new int[localJSONArray2.length()];
        for (int j = 0; j < localJSONArray2.length(); j++) {
            locala1.er[j] = localJSONArray2.getInt(j);
        }
        JSONArray localJSONArray3 = localJSONObject.optJSONArray("facePointOffset");
        if (null != localJSONArray3) {
            if (localJSONArray3.length() % 5 != 0) {
                throw new JSONException("facePointOffset is not multiple of 5");
            }
            locala1.es = new MakeupData.b[localJSONArray3.length() / 5];
            for (int k = 0; k < locala1.es.length; k++) {
                MakeupData.b localb = new MakeupData.b();
                localb.ew = localJSONArray3.getInt(5 * k);
                localb.ex = localJSONArray3.getInt(5 * k + 1);
                localb.ey = ((float) localJSONArray3.getDouble(5 * k + 2));
                localb.ez = localJSONArray3.getInt(5 * k + 3);
                localb.eA = ((float) localJSONArray3.getDouble(5 * k + 4));
                locala1.es[k] = localb;
            }
        } else {
            locala1.es = new MakeupData.b[0];
        }
        JSONArray localJSONArray4 = localJSONObject.getJSONArray("resFacePoints");
        if (localJSONArray4.length() != 212) {
            throw new JSONException("resFacePoints size is error");
        }
        locala1.et = new PointF[106];
        for (int m = 0; m < 106; m++) {
            locala1.et[m] = new PointF((float) localJSONArray4.getDouble(2 * m), (float) localJSONArray4.getDouble(2 * m + 1));
        }
        locala1.ev = (localJSONObject.optInt("inheritoffset") == 1);
        locala.eo.add(locala1);
    }
    return locala;
}