Java Code Examples for org.json.JSONArray

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudViewParser.java

  20 
vote

public List<CloudView> parseFromString(String json) throws JSONException {
  JSONArray outlineArray=new JSONArray(json);
  List<CloudView> views=new ArrayList<CloudView>();
  for (int i=0; i < outlineArray.length(); i++) {
    JSONObject appObject=outlineArray.getJSONObject(i);
    String title=appObject.getString("title");
    String viewName=appObject.getString("name");
    views.add(new CloudView(title,viewName));
  }
  return views;
}
 

Example 2

From project andlytics, under directory /src/com/github/andlyticsproject/admob/.

Source file: AdmobRequest.java

  19 
vote

public static String login(String email,String password) throws NetworkException, AdmobInvalidTokenException, AdmobGenericException, AdmobInvalidRequestException, AdmobRateLimitExceededException {
  String token=null;
  String params="client_key=" + clientKey + "&email="+ URLEncoder.encode(email)+ "&password="+ URLEncoder.encode(password);
  try {
    Log.d(TAG,email + " admob login request");
    JSONArray data=getResponse("auth","login",params,true,true);
    token=data.getJSONObject(0).getString("token");
  }
 catch (  JSONException e) {
    throw new AdmobGenericException(e);
  }
  return token;
}
 

Example 3

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/builder/identity/.

Source file: GroupUsersObjectBuilder.java

  18 
vote

@Override @SuppressWarnings("unchecked") public JSONObject createJsonObject(Object modelObject) throws JSONException {
  JSONObject result=new JSONObject();
  Map<String,Object> model=getModelAsMap(modelObject);
  List<User> users=(List<User>)model.get("users");
  JSONArray groupsArray=JSONUtil.putNewArray(result,"data");
  if (users != null) {
    for (    User user : users) {
      groupsArray.put(converter.getJSONObject(user));
    }
  }
  JSONUtil.putPagingInfo(result,model);
  return result;
}
 

Example 4

From project agraph-java-client, under directory /src/com/franz/agraph/repository/.

Source file: AGFreetextIndexConfig.java

  18 
vote

private List<URI> initPredicates(JSONObject config){
  List<URI> predList=new ArrayList<URI>();
  JSONArray preds=config.optJSONArray(PREDICATES);
  if (preds != null) {
    for (int i=0; i < preds.length(); i++) {
      String uri_nt=preds.optString(i);
      URI uri=NTriplesUtil.parseURI(uri_nt,vf);
      predList.add(uri);
    }
  }
  return predList;
}
 

Example 5

From project AlarmApp-Android, under directory /src/org/alarmapp/web/json/.

Source file: JsonUtil.java

  18 
vote

public static boolean parseSmartphoneCreateResult(String jsonDocument) throws JSONException {
  JSONArray array=new JSONArray(jsonDocument);
  if (array.length() == 0) {
    return false;
  }
  JSONObject obj=(JSONObject)array.get(0);
  int pk=obj.getInt("pk");
  LogEx.verbose("Smartphone PK is " + pk);
  if (pk > 0) {
    return true;
  }
  return false;
}
 

Example 6

From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/.

Source file: BillingController.java

  18 
vote

/** 
 * Parse all purchases from the JSON data received from the Market Billing service.
 * @param data JSON data received from the Market Billing service.
 * @return list of purchases.
 * @throws JSONException if the data couldn't be properly parsed.
 */
private static List<Transaction> parsePurchases(JSONObject data) throws JSONException {
  ArrayList<Transaction> purchases=new ArrayList<Transaction>();
  JSONArray orders=data.optJSONArray(JSON_ORDERS);
  int numTransactions=0;
  if (orders != null) {
    numTransactions=orders.length();
  }
  for (int i=0; i < numTransactions; i++) {
    JSONObject jElement=orders.getJSONObject(i);
    Transaction p=Transaction.parse(jElement);
    purchases.add(p);
  }
  return purchases;
}
 

Example 7

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxAuthActivity.java

  18 
vote

public void youtubeCb(String url,JSONObject jo,AjaxStatus status){
  if (jo != null) {
    JSONArray entries=jo.optJSONObject("feed").optJSONArray("entry");
    showResult(jo);
  }
 else {
    showError(status);
  }
}
 

Example 8

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: Report.java

  18 
vote

/** 
 * Adds the log entries to the report.
 * @param report the report
 * @throws JSONException if the log entries cannot be added
 */
private void addLog(JSONObject report) throws JSONException {
  JSONObject logs=new JSONObject();
  List<String> list=Log.getReportedEntries();
  if (list != null) {
    logs.put("numberOfEntry",list.size());
    JSONArray array=new JSONArray();
    for (    String s : list) {
      array.put(s);
    }
    logs.put("log",array);
  }
  report.put("log",logs);
}
 

Example 9

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: AnkiDroidProxy.java

  18 
vote

public double modified(){
  double lastModified=0;
  connect();
  try {
    JSONArray deckInfo=mDecks.getJSONArray(mDeckName);
    lastModified=deckInfo.getDouble(0);
  }
 catch (  JSONException e) {
    Log.i(AnkiDroidApp.TAG,"JSONException = " + e.getMessage());
  }
  return lastModified;
}
 

Example 10

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/handlers/.

Source file: StatusHandler.java

  18 
vote

/** 
 * Handle the list_jobs AJAX command.
 */
private static JSONObject handleListJobs(String cursor,int count) throws JSONException {
  Collection<MapperStateEntity<?,?,?,?>> states=new ArrayList<MapperStateEntity<?,?,?,?>>();
  Cursor newCursor=MapperStateEntity.getMapReduceStates(cursor,count,states);
  JSONArray jobs=new JSONArray();
  for (  MapperStateEntity<?,?,?,?> state : states) {
    jobs.put(state.toJson(false));
  }
  JSONObject retValue=new JSONObject();
  retValue.put("jobs",jobs);
  if (newCursor != null) {
    retValue.put("cursor",newCursor.toWebSafeString());
  }
  return retValue;
}
 

Example 11

From project azkaban, under directory /azkaban/src/java/azkaban/util/json/.

Source file: JSONUtils.java

  18 
vote

/** 
 * Creates a json string from Map/List/Primitive object.
 * @param obj
 * @return
 */
public static String toJSONString(List<?> list){
  JSONArray jsonList=new JSONArray(list);
  try {
    return jsonList.toString();
  }
 catch (  Exception e) {
    return "";
  }
}
 

Example 12

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/repository/.

Source file: Repositories.java

  18 
vote

/** 
 * Gets repository names.
 * @return repository names, for example,<pre> [ "repository1", "repository2", .... ] </pre>
 */
public static JSONArray getRepositoryNames(){
  final JSONArray ret=new JSONArray();
  if (null == repositoriesDescription) {
    LOGGER.log(Level.INFO,"Not found repository description[repository.json] file under classpath");
    return ret;
  }
  final JSONArray repositories=repositoriesDescription.optJSONArray("repositories");
  for (int i=0; i < repositories.length(); i++) {
    final JSONObject repository=repositories.optJSONObject(i);
    ret.put(repository.optString("name"));
  }
  return ret;
}
 

Example 13

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: SitemapProcessor.java

  18 
vote

/** 
 * Adds archives (archive-articles) into the specified sitemap.
 * @param sitemap the specified sitemap
 * @param preference the specified preference
 * @throws Exception exception
 */
private void addArchives(final Sitemap sitemap,final JSONObject preference) throws Exception {
  final String host=preference.getString(Preference.BLOG_HOST);
  final JSONObject result=archiveDateRepository.get(new Query());
  final JSONArray archiveDates=result.getJSONArray(Keys.RESULTS);
  for (int i=0; i < archiveDates.length(); i++) {
    final JSONObject archiveDate=archiveDates.getJSONObject(i);
    final long time=archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
    final String dateString=ArchiveDate.DATE_FORMAT.format(time);
    final URL url=new URL();
    url.setLoc("http://" + host + "/archives/"+ dateString);
    sitemap.addURL(url);
  }
}
 

Example 14

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/data/.

Source file: CategoryProvider.java

  17 
vote

@Override public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder){
  JSONArray array=new JSONArray();
  try {
    String categoryId=JsonData.VALUE_NULL;
switch (uriMatcher.match(uri)) {
case CATEGORIES_ID:
      categoryId=uri.getLastPathSegment();
case CATEGORIES:
    JSONObject parent=categories.getJSONObject(categoryId);
  if (parent.has(JsonData.PARAM_CATEGORY_CHILDREN)) {
    JSONArray subset=parent.getJSONArray(JsonData.PARAM_CATEGORY_CHILDREN);
    for (int i=0; i < subset.length(); i++) {
      JSONObject obj=categories.getJSONObject(subset.getString(i));
      obj.put(BaseColumns._ID,(long)Integer.valueOf(subset.getString(i)));
      array.put(obj);
    }
  }
break;
case CATEGORY_ID:
categoryId=uri.getLastPathSegment();
array.put(categories.getJSONObject(categoryId));
Log.d(Constants.PROJECT_TAG,"category returned = " + categories.getJSONObject(categoryId));
break;
default :
return null;
}
}
 catch (NumberFormatException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
Cursor c=new JSONCursor(array,projection);
if (c != null) c.setNotificationUri(getContext().getContentResolver(),uri);
return c;
}
 

Example 15

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Skandiabanken.java

  17 
vote

@Override public void update() throws BankException, LoginException, BankChoiceException {
  super.update();
  if (username == null || password == null || username.length() == 0 || password.length() == 0)   throw new LoginException(res.getText(R.string.invalid_username_password).toString());
  login();
  String accountsUrl=getBaseUrlWithCustomerOwner() + "/customer/" + customerId+ "/accounts";
  try {
    String accountsJsonString=urlopen.open(accountsUrl);
    JSONArray json=new JSONArray(accountsJsonString);
    for (int i=0; i < json.length(); i++) {
      JSONObject acountJsonObj=json.getJSONObject(i);
      String name=acountJsonObj.optString("alias");
      if (name.length() != 0)       name+=" - ";
      name+=acountJsonObj.getString("accountNumber");
      String balanceString=acountJsonObj.getString("amount");
      String id=acountJsonObj.getString("id");
      int type=Account.REGULAR;
      Account account=new Account(name,Helpers.parseBalance(balanceString),id,type);
      accounts.add(account);
    }
  }
 catch (  IOException e) {
    throw new BankException("IOException " + e.getMessage());
  }
catch (  JSONException e) {
    throw new BankException("Ov?ntat svarsformat " + e.getMessage());
  }
}
 

Example 16

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.

Source file: NetworkUtilities.java

  17 
vote

/** 
 * Fetches the list of friend data updates from the server
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(PARAM_USERNAME,account.name));
  params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken));
  if (lastUpdated != null) {
    final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated)));
  }
  Log.i(TAG,params.toString());
  HttpEntity entity=null;
  entity=new UrlEncodedFormEntity(params);
  final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI);
  post.addHeader(entity.getContentType());
  post.setEntity(entity);
  maybeCreateHttpClient();
  final HttpResponse resp=mHttpClient.execute(post);
  final String response=EntityUtils.toString(resp.getEntity());
  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    final JSONArray friends=new JSONArray(response);
    Log.d(TAG,response);
    for (int i=0; i < friends.length(); i++) {
      friendList.add(User.valueOf(friends.getJSONObject(i)));
    }
  }
 else {
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
      Log.e(TAG,"Authentication exception in fetching remote contacts");
      throw new AuthenticationException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 17

From project android_7, under directory /src/org/immopoly/android/model/.

Source file: Flats.java

  17 
vote

public void parse(JSONObject obj){
  try {
    Flat item;
    JSONObject resultList=obj.getJSONObject("resultlist.resultlist");
    JSONArray resultEntries=resultList.optJSONArray("resultlistEntries");
    if (resultEntries != null && resultEntries.length() > 0) {
      JSONObject flatsObj=resultEntries.getJSONObject(0);
      JSONArray resultEntry=flatsObj.optJSONArray("resultlistEntry");
      if (resultEntry == null) {
        JSONObject flatObj=flatsObj.optJSONObject("resultlistEntry");
        if (flatObj != null) {
          item=new Flat(flatObj);
          add(item);
          if (flatObj.has("distance"))           Log.d(Const.LOG_TAG,"Parsed 1 flat. Max distance: " + flatObj.get("distance"));
        }
      }
 else {
        if (resultEntries != null && resultEntry != null) {
          double maxDistance=0;
          for (int i=0; i < resultEntry.length(); i++) {
            JSONObject flatObj=resultEntry.getJSONObject(i);
            item=new Flat(flatObj);
            add(item);
            if (flatObj.has("distance")) {
              double dist=flatObj.getDouble("distance");
              if (dist > maxDistance)               maxDistance=dist;
            }
          }
          Log.d(Const.LOG_TAG,"Parsed " + resultEntry.length() + " flats. Max distance: "+ maxDistance);
        }
      }
    }
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
}
 

Example 18

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionBasicAuth.java

  17 
vote

@Override public JSONArray getHomeTimeline(String sinceId,int limit) throws ConnectionException {
  setSinceId(sinceId);
  setLimit(limit);
  String url=getApiUrl(apiEnum.STATUSES_HOME_TIMELINE);
  url+="?count=" + mLimit;
  if (mSinceId.length() > 1) {
    url+="&since_id=" + mSinceId;
  }
  JSONArray jArr=null;
  String request=getRequest(url);
  try {
    jArr=new JSONArray(request);
  }
 catch (  JSONException e) {
    try {
      JSONObject jObj=new JSONObject(request);
      String error=jObj.optString("error");
      if ("Could not authenticate you.".equals(error)) {
        throw new ConnectionException(error);
      }
    }
 catch (    JSONException e1) {
      throw new ConnectionException(e);
    }
  }
  return jArr;
}
 

Example 19

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionBasicAuth.java

  17 
vote

@Override public JSONArray getFriendsTimeline(long sinceId,int limit) throws ConnectionException {
  setSinceId(sinceId);
  setLimit(limit);
  String url=STATUSES_FRIENDS_TIMELINE_URL;
  url+="?count=" + mLimit;
  if (mSinceId > 0) {
    url+="&since_id=" + mSinceId;
  }
  JSONArray jArr=null;
  String request=getRequest(url);
  try {
    jArr=new JSONArray(request);
  }
 catch (  JSONException e) {
    try {
      JSONObject jObj=new JSONObject(request);
      String error=jObj.optString("error");
      if ("Could not authenticate you.".equals(error)) {
        throw new ConnectionException(error);
      }
    }
 catch (    JSONException e1) {
      throw new ConnectionException(e);
    }
  }
  return jArr;
}
 

Example 20

From project apps-for-android, under directory /Panoramio/src/com/google/android/panoramio/.

Source file: ImageManager.java

  17 
vote

private void parse(JSONObject json){
  try {
    JSONArray array=json.getJSONArray("photos");
    int count=array.length();
    for (int i=0; i < count; i++) {
      JSONObject obj=array.getJSONObject(i);
      long id=obj.getLong("photo_id");
      String title=obj.getString("photo_title");
      String owner=obj.getString("owner_name");
      String thumb=obj.getString("photo_file_url");
      String ownerUrl=obj.getString("owner_url");
      String photoUrl=obj.getString("photo_url");
      double latitude=obj.getDouble("latitude");
      double longitude=obj.getDouble("longitude");
      Bitmap b=BitmapUtils.loadBitmap(thumb);
      if (title == null) {
        title=mContext.getString(R.string.untitled);
      }
      final PanoramioItem item=new PanoramioItem(id,thumb,b,(int)(latitude * Panoramio.MILLION),(int)(longitude * Panoramio.MILLION),title,owner,ownerUrl,photoUrl);
      final boolean done=i == count - 1;
      mHandler.post(new Runnable(){
        public void run(){
          sInstance.mLoading=!done;
          sInstance.add(item);
        }
      }
);
    }
  }
 catch (  JSONException e) {
    Log.e(TAG,e.toString());
  }
}
 

Example 21

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/extract/.

Source file: RealCDXExtractorOutput.java

  17 
vote

private String extractHTMLRobots(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,"name",null);
        if (name != null) {
          if (name.toLowerCase().equals("robots")) {
            String content=scanHeadersLC(meta,"content",null);
            if (content != null) {
              return parseRobotInstructions(content);
            }
          }
        }
      }
    }
  }
  return "-";
}
 

Example 22

From project android-tether, under directory /src/og/android/tether/.

Source file: MainActivity.java

  16 
vote

private synchronized void updateRSSView(String JSONrss){
  Log.d(MSG_TAG,"Intent JSONRSS: " + JSONrss);
  try {
    this.rssAdapter.clear();
    this.rssAdapter.notifyDataSetChanged();
    this.jsonRssArray=new JSONArray(JSONrss);
    for (int i=0; i < jsonRssArray.length(); i++) {
      JSONObject jsonRssItem=jsonRssArray.getJSONObject(i);
      this.rssAdapter.add(Html.fromHtml(jsonRssItem.getString("title") + " - <i>" + jsonRssItem.getString("creator")+ "</i>"));
    }
    if (jsonRssArray.length() > 0 && !this.application.settings.getBoolean("rss_closed",false))     this.rssPanel.setOpen(true,true);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
}
 

Example 23

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: JsonHttpResponseHandler.java

  15 
vote

protected void handleSuccessJsonMessage(Object jsonResponse){
  if (jsonResponse instanceof JSONObject) {
    onSuccess((JSONObject)jsonResponse);
  }
 else   if (jsonResponse instanceof JSONArray) {
    onSuccess((JSONArray)jsonResponse);
  }
 else {
    onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()),(JSONObject)null);
  }
}
 

Example 24

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/service/.

Source file: UpdaterService.java

  15 
vote

public boolean populate(JSONArray jsonArray){
  try {
    int myVersionCode=getPackageManager().getPackageInfo(getPackageName(),0).versionCode;
    JSONObject manifest=null;
    for (int i=0; i < jsonArray.length(); i++) {
      manifest=jsonArray.getJSONObject(i);
      if (manifest.getInt("min-apk-version") <= myVersionCode)       break;
    }
    if (manifest == null)     return false;
    version=manifest.getString("version");
    versionCode=manifest.getInt("version-code");
    String abi=Build.CPU_ABI.split("-")[0];
    JSONObject binaryInfo=manifest.getJSONObject(abi);
    binaryUrl=binaryInfo.getString("binary");
    binaryMd5=binaryInfo.getString("binary-md5sum");
  }
 catch (  JSONException e) {
    return false;
  }
catch (  NameNotFoundException e) {
    Log.e(TAG,"Divided by zero...",e);
    return false;
  }
  if (version == null || versionCode == 0 || binaryUrl == null || binaryMd5 == null) {
    return false;
  }
  return true;
}