code: protected final JSONArray getPages(Iterator<Page> pages, int depth, PageFilter pageFilter) throws JSONException {
      JSONArray pagesArray = new JSONArray();
  
      while (pages.hasNext()) {
        Page page = pages.next();
  
        // map page attributes to JSON object
        JSONObject pageObject = getPage(page);
        if (pageObject != null) {
  
          // write children
          Iterator<Page> children = listChildren(page.adaptTo(Resource.class), pageFilter);
          if (!children.hasNext()) {
            pageObject.put("leaf", true);
          }
          else if (depth < getMaxDepth() - 1) {
            pageObject.put("children", getPages(children, depth + 1, pageFilter));
          }
  
          pagesArray.put(pageObject);
        }
      }
  
      return pagesArray;
    }
docs: Generate JSON objects for pages.
  @param pages Child page iterator
  @param depth Depth
  @param pageFilter Page filter
  @return Page array
  @throws JSONException JSON exception