public static void parseJSON(JSONObject routesJson) throws JSONException {
   JSONArray jRoutes = new JSONArray();
   BusManager sharedManager = BusManager.getBusManager();
   if (routesJson != null)
     jRoutes = routesJson.getJSONObject(BusManager.TAG_DATA).getJSONArray("72");
   for (int j = 0; j < jRoutes.length(); j++) {
     JSONObject routeObject = jRoutes.getJSONObject(j);
     String routeLongName = routeObject.getString(BusManager.TAG_LONG_NAME);
     String routeID = routeObject.getString(BusManager.TAG_ROUTE_ID);
     Route r = sharedManager.getRoute(routeLongName, routeID);
     JSONArray stops = routeObject.getJSONArray(BusManager.TAG_STOPS);
     for (int i = 0; i < stops.length(); i++) {
       r.addStop(i, sharedManager.getStopByID(stops.getString(i)));
     }
     JSONArray segments = routeObject.getJSONArray(BusManager.TAG_SEGMENTS);
     if (BuildConfig.DEBUG)
       Log.v(
           MainActivity.REFACTOR_LOG_TAG,
           "Found " + segments.length() + " segments for route " + routeID);
     for (int i = 0; i < segments.length(); i++) {
       // if (BuildConfig.DEBUG) Log.v("MapDebugging", "parseJSON of Route adding segment ID " +
       // segments.getJSONArray(i).getString(0) + " for " + routeID + "(" +
       // r.getSegmentIDs().size() + " total)");
       r.getSegmentIDs().add(segments.getJSONArray(i).getString(0));
     }
     sharedManager.addRoute(r);
     // if (BuildConfig.DEBUG) Log.v("JSONDebug", "Route name: " + routeLongName + " | ID:" +
     // routeID + " | Number of stops: " + sharedManager.getRouteByID(routeID).getStops().size());
   }
 }
  private void parseItems(List<PhotographerPlace> items, JSONObject jsonBody)
      throws IOException, JSONException {
    JSONArray resultJsonArray = jsonBody.getJSONArray("results");

    for (int i = 0; i < resultJsonArray.length(); i++) {
      PhotographerPlace item = new PhotographerPlace();
      JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
      if (resultJsonObject.has("photos")) {
        JSONArray photoJsonArray = resultJsonObject.getJSONArray("photos");
        if (photoJsonArray.length() > 0) {
          for (int j = 0; j < photoJsonArray.length(); j++) {
            JSONObject photoJsonObject = photoJsonArray.getJSONObject(j);
            item.setIconURL(photoJsonObject.getString("photo_reference"));
          }
        }
      }
      item.setAddress(resultJsonObject.getString("formatted_address"));
      item.setName(resultJsonObject.getString("name"));
      item.setID(resultJsonObject.getString("place_id"));

      // item.setPriceLevel(resultJsonObject.getString("price_level"));
      // item.setRating(resultJsonObject.getString("rating"));
      items.add(item);
    }
  }
  private ServerStatus getSpaces(List<Space> spaces, JSONObject orgJSON) throws Exception {
    URI targetURI = URIUtil.toURI(target.getUrl());
    URI spaceURI = targetURI.resolve(orgJSON.getJSONObject("entity").getString("spaces_url"));

    GetMethod getDomainsMethod = new GetMethod(spaceURI.toString());
    HttpUtil.configureHttpMethod(getDomainsMethod, target);
    getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$

    ServerStatus status = HttpUtil.executeMethod(getDomainsMethod);
    if (!status.isOK()) return status;

    /* extract available spaces */
    JSONObject orgs = status.getJsonData();

    if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
    }

    /* look if the domain is available */
    int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
    for (int k = 0; k < resources; ++k) {
      JSONObject spaceJSON =
          orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
      spaces.add(new Space().setCFJSON(spaceJSON));
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
  }
  public void testStreamArray() throws IOException, JSONException {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
    Display display = new Display();
    Shell shell = new Shell(display);
    writer.appendPayload(
        WidgetUtil.getId(shell),
        IProtocolConstants.PAYLOAD_CONSTRUCT,
        "key",
        new Integer[] {new Integer(1), new Integer(2)});
    writer.appendPayload(
        WidgetUtil.getId(shell), IProtocolConstants.PAYLOAD_CONSTRUCT, "key2", new Boolean(true));

    writer.finish();
    String actual = stringWriter.getBuffer().toString();
    JSONObject message = new JSONObject(actual);
    JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
    JSONObject widgetObject = widgetArray.getJSONObject(0);
    JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
    JSONArray array = payload.getJSONArray("key");
    assertEquals(1, array.getInt(0));
    assertEquals(2, array.getInt(1));
    assertTrue(payload.getBoolean("key2"));
  }
  @Test
  public void testToString() throws Exception {
    ProductBagApi bags = new ProductBagApi(new MockContext());
    bags.addProduct("some bag name", new Product.Builder("product name", "product sku", 1).build());
    bags.addProduct(
        "some bag name", new Product.Builder("product name 2", "product sku 2", 1).build());
    bags.addProduct(
        "some bag name 2", new Product.Builder("product name 3", "product sku 3", 1).build());
    bags.addProduct("some bag name 3", null);
    JSONObject json = new JSONObject(bags.toString());
    assertTrue(json.has("some bag name"));
    JSONObject bag1 = json.getJSONObject("some bag name");
    assertTrue(bag1.has("pl"));
    JSONArray products1 = bag1.getJSONArray("pl");
    assertEquals(2, products1.length());
    JSONObject bag2 = json.getJSONObject("some bag name 2");
    assertTrue(bag2.has("pl"));
    JSONArray products2 = bag2.getJSONArray("pl");
    assertEquals(1, products2.length());

    JSONObject bag3 = json.getJSONObject("some bag name 3");
    assertTrue(bag3.has("pl"));
    JSONArray products3 = bag3.getJSONArray("pl");
    assertEquals(0, products3.length());
  }
Example #6
0
  @Override
  public void parseJson(JSONObject json) throws JSONException {
    super.parseJson(json);

    if (json != null) {

      JSONObject skills = json.getJSONObject("skills");

      JSONArray jsonArray = skills.getJSONArray("active");

      int len = jsonArray.length();

      if (len > 0) {
        activeSkills = new LinkedList<Skill>();
        parseSkill(activeSkills, Skill.SKILL_TYPE_ACTIVE, jsonArray);
      }

      jsonArray = skills.getJSONArray("passive");

      len = jsonArray.length();

      if (len > 0) {
        passiveSkills = new LinkedList<Skill>();
        parseSkill(passiveSkills, Skill.SKILL_TYPE_PASSIVE, jsonArray);
      }
    }
  }
 public void testMessageWithDestroy() throws IOException, JSONException {
   StringWriter stringWriter = new StringWriter();
   PrintWriter printWriter = new PrintWriter(stringWriter);
   ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
   Display display = new Display();
   Shell shell = new Shell(display);
   Button button = new Button(shell, SWT.PUSH);
   writer.addDestroyPayload(WidgetUtil.getId(button));
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   Object payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
   writer.addDestroyPayload(WidgetUtil.getId(shell));
   writer.finish();
   String shellId = WidgetUtil.getId(shell);
   actual = stringWriter.getBuffer().toString();
   message = new JSONObject(actual);
   widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   widgetObject = widgetArray.getJSONObject(1);
   type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(shellId, actualId);
   payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
 }
  @Override
  protected ArrayList<String> doInBackground(String... params) {
    try {
      String urlString = params[0];
      url = new URL(urlString);
      inputStream = url.openConnection().getInputStream();
      String response = InstaImpl.streamToString(inputStream);
      Log.e(TAG, "Response string is " + urlString);
      JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue();
      JSONArray jsonArray = jsonObject.getJSONArray("data");
      //			 Log.e(TAG, "JSON Array is " + jsonArray.toString());

      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject currentObject = jsonArray.getJSONObject(i);

        JSONArray tagsArray = currentObject.getJSONArray("tags");
        // check for selfie tag
        for (int j = 0; j < tagsArray.length(); j++) {
          if (tagsArray.optString(j).equals("selfie")) {
            JSONObject mainImageJsonObject =
                currentObject.getJSONObject("images").getJSONObject("low_resolution");
            String imageUrlString = mainImageJsonObject.getString("url");
            Log.e(TAG, "URL is: " + imageUrlString);
            imageUrlStrings.add(imageUrlString);
          }
        }
        Log.e(TAG, "Tags are " + tagsArray.toString());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return imageUrlStrings;
  }
Example #9
0
  /** Parses the given contents containing a source map. */
  public void parse(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier)
      throws SourceMapParseException {
    try {
      // Check basic assertions about the format.
      int version = sourceMapRoot.getInt("version");
      if (version != 3) {
        throw new SourceMapParseException("Unknown version: " + version);
      }

      String file = sourceMapRoot.getString("file");
      if (file.isEmpty()) {
        throw new SourceMapParseException("File entry is missing or empty");
      }

      if (sourceMapRoot.has("sections")) {
        // Looks like a index map, try to parse it that way.
        parseMetaMap(sourceMapRoot, sectionSupplier);
        return;
      }

      lineCount = sourceMapRoot.getInt("lineCount");
      String lineMap = sourceMapRoot.getString("mappings");

      sources = getJavaStringArray(sourceMapRoot.getJSONArray("sources"));
      names = getJavaStringArray(sourceMapRoot.getJSONArray("names"));

      lines = Lists.newArrayListWithCapacity(lineCount);

      new MappingBuilder(lineMap).build();
    } catch (JSONException ex) {
      throw new SourceMapParseException("JSON parse exception: " + ex);
    }
  }
  // parse JSON object
  public static void readJson(String jsonStr) throws JSONException {

    JSONObject obj = new JSONObject(jsonStr);
    JSONObject castObj = obj.getJSONObject("Products");
    JSONArray movies = castObj.getJSONArray("Movie");

    for (int i = 0; i < movies.length(); i++) {
      JSONObject movie = movies.getJSONObject(i);
      imgs = movie.getJSONObject("BoxArtImages");
      links = imgs.getJSONArray("link");
      castLinks = links.getJSONObject(0);
      titleStr = movie.getString("Title");
      linkStr = castLinks.getString("@href");

      // don't get the Blue Ray movie titles (they will be retrieve when getting the local machines
      // inventory)
      if (!movie.getString("Title").toLowerCase().contains("(Blu-ray)".toLowerCase())) {
        titles.add(titleStr);
        imgLinks.add(linkStr);
        Log.i("Movie:", "Title: " + titleStr);
        Log.i("Movie:", "Link: " + linkStr);
      }
    }

    // call the loadData function to load data into the ListView
    MainActivity.loadData();
  }
  private void FillGridView(String s) {

    JSONObject json = null;
    String[] disponible = new String[5];

    JSONObject dataJson;
    JSONArray arrayjson = null;
    try {

      json = new JSONObject(s);

      String nombre = json.getString("name");
      arrayjson = json.getJSONArray("available_markets");
      String avalible = "";
      if (arrayjson.length() < 5)
        for (int k = 0; k < arrayjson.length(); k++) {

          disponible[k] = arrayjson.get(k).toString();
          avalible += disponible[k] + ",";
        }

      String play = json.getJSONObject("external_urls").getString("spotify");
      JSONArray images = json.getJSONArray("images");
      String imgurl;
      if (images.length() > 0) imgurl = images.getJSONObject(0).getString("url");
      else imgurl = null;
      itemAlbum.add(new AlbumItem(nombre, imgurl, avalible, play));

      mAdapter = new CardAdapter(itemAlbum, this);
      mRecyclerView.setAdapter(mAdapter);

    } catch (Exception e) {
      Log.e("error", e.toString());
    }
  }
 public boolean isTagsPresent(String data, JSONObject tags) {
   if (tags == null) return true;
   else {
     int index;
     JSONArray names = tags.names();
     try {
       JSONObject jsonData = new JSONObject(data);
       JSONObject dataTags = new JSONObject(jsonData.getString("tags"));
       for (index = 0; index < names.length(); index++) {
         String name = names.getString(index);
         JSONArray dataTagArray = dataTags.getJSONArray(name);
         JSONArray tagArray = tags.getJSONArray(name);
         boolean isFound = false;
         for (int iteri = 0; iteri < tagArray.length(); iteri++) {
           for (int iterj = 0; iterj < dataTagArray.length(); iterj++) {
             if (tagArray.getString(iteri).contentEquals(dataTagArray.getString(iterj)))
               isFound = true;
           }
         }
         if (dataTagArray.length() * tagArray.length() == 0) isFound = true;
         if (!isFound) return false;
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return true;
 }
  private Recipe getRecipe(JSONArray recipesArray, int recipe_id) {

    Recipe recipe = new Recipe();
    for (int i = 0; i < recipesArray.length(); i++) {

      try {
        if (recipe_id == (recipesArray.getJSONObject(i).getJSONObject("recipe")).getInt(KEY_ID)) {
          JSONObject jsonObject = recipesArray.getJSONObject(i).getJSONObject("recipe");
          recipe.setId(jsonObject.getInt(KEY_ID));
          recipe.setTitle(jsonObject.getString(KEY_TITLE));
          recipe.setDescription((jsonObject.getString(KEY_DESCRIPTION)));
          recipe.setImageUrl(jsonObject.getString("thumbnail_image_url"));
          recipe.setInstructions(jsonObject.getJSONArray(KEY_INSTRUCTIONS));
          recipe.setCalories(jsonObject.getInt(KEY_CALORIES));
          recipe.setProtein(jsonObject.getInt(KEY_PROTEIN));
          recipe.setCarbs(jsonObject.getInt(KEY_CARB));
          recipe.setFat(jsonObject.getInt(KEY_FAT));
          recipe.setIngredients(jsonObject.getJSONArray(KEY_INGREDIENTS));
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    return recipe;
  }
  // 对address.json进行解析
  private List<Dialog_forlist> jSON2List2(String jsonPath) throws JSONException {
    List<Dialog_forlist> list = new ArrayList<>();
    InputStream is = AssetManagerUtils.getData(jsonPath, ReleaseActivity.this);
    String str = StreamTools.readStream(is);

    JSONObject object = new JSONObject(str);
    JSONArray jsonArray = object.getJSONArray("city");
    JSONObject jsonObject = jsonArray.getJSONObject(0);
    JSONArray jsonArray1 = jsonObject.getJSONArray("tdistrict");
    for (int i = 0; i < jsonArray1.length(); i++) {
      Dialog_forlist dialog_forlist = new Dialog_forlist();
      List<String> list_city = new ArrayList<>();
      if (i == 0) {
        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
        dialog_forlist.setName(jsonObject1.getString("name"));
        list_city.add("不限");
        dialog_forlist.setList(list_city);
      } else {
        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
        dialog_forlist.setName(jsonObject1.getString("name"));
        JSONArray jsonArray2 = jsonObject1.getJSONArray("bussinessareaList");
        for (int j = 0; j < jsonArray2.length(); j++) {
          JSONObject jsonObject2 = jsonArray2.getJSONObject(j);
          list_city.add(jsonObject2.getString("name"));
        }
        dialog_forlist.setList(list_city);
      }
      list.add(dialog_forlist);
    }

    return list;
  }
Example #15
0
  public static RouteModel ParseJSON(String json) throws JSONException {
    RouteModel route = new RouteModel();

    ArrayList<Step> localSteps = new ArrayList<RouteModel.Step>();

    // JSONをパース
    JSONObject obj = new JSONObject(json);
    JSONArray routelist = obj.getJSONArray("routes");
    JSONObject mainroute = routelist.getJSONObject(0);
    JSONArray legslist = mainroute.getJSONArray("legs");
    for (int i = 0; i < legslist.length(); i++) {
      JSONArray steps = legslist.getJSONObject(i).getJSONArray("steps");
      for (int j = 0; j < steps.length(); j++) {
        Step s = route.new Step();
        JSONObject step = steps.getJSONObject(j);
        s.distance = step.getJSONObject("distance").getInt("value");
        s.duration = step.getJSONObject("duration").getInt("value");
        JSONObject st = step.getJSONObject("start_location");
        s.start_addr =
            new GeoPoint((int) (st.getDouble("lat") * 1E6), (int) (st.getDouble("lng") * 1E6));
        JSONObject en = step.getJSONObject("end_location");
        s.end_addr =
            new GeoPoint((int) (en.getDouble("lat") * 1E6), (int) (en.getDouble("lng") * 1E6));
        s.instruction = step.getString("html_instructions");
        localSteps.add(s);
      }
    }

    route.steps = new Step[localSteps.size()];
    for (int i = 0; i < localSteps.size(); i++) {
      route.steps[i] = localSteps.get(i);
    }

    return route;
  }
  public void Parse(JSONObject json) {

    try {
      JSONObject response_object = json.getJSONObject(response);
      JSONObject data_array = response_object.getJSONObject(data);
      JSONArray result_array = data_array.getJSONArray(result);
      watcard_vendor_objects = new WatcardVendorObject[result_array.length()];

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

        JSONObject vendor_details = result_array.getJSONObject(i);
        String vendor_name = MenuUtilities.checkName(vendor_details.getString(name));
        String location_name = vendor_details.getString(location);
        String telephone_number = vendor_details.getString(telephone);

        result_array = data_array.getJSONArray(result);
        watcard_vendor_objects[i] =
            new WatcardVendorObject(vendor_name, location_name, telephone_number);
      }

      init.initWatcardLocations(watcard_vendor_objects);

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Example #17
0
  public YoudaoFanyiItem(String jsonItemString) {
    super();
    webItems = new ArrayList<WebItem>();
    if (TextUtils.isEmpty(jsonItemString)) return;
    try {
      JSONObject item = new JSONObject(jsonItemString);
      //			String translation_array = item.getJSONArray("translation").toString();
      //			if(translation_array.length()>4){
      //				this.translation = translation_array.substring(2,translation_array.length()-2);
      //			}
      this.translation = parseJsonArray2String(item.getJSONArray("translation"));
      if (item.has("basic")) {
        JSONObject basic = item.getJSONObject("basic");
        this.basic = basic.toString();
        this.basic_explains =
            parseJsonArray2String(
                basic.getJSONArray(
                    "explains")); // basic_explains_array.substring(1,
                                  // basic_explains_array.length()-1).replaceAll(",", "\n");
        this.basic_phonetic = basic.getString("phonetic");
      }
      this.query = item.getString("query");

      this.errorCode = item.getInt("errorCode");
      setWeb(item.getJSONArray("web").toString());
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #18
0
  private IGeometry decodeGeometry(JSONObject object) throws JSONException {
    IGeometry geom = null;
    LineString[] lineStrings;
    if (object.get("type").equals("MultiLineString")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      int size = coordinates.length();
      lineStrings = new LineString[size];
      LineString l;
      for (int i = 0; i < size; i++) {
        JSONArray lineStrCoord = coordinates.getJSONArray(i);
        double[][] coords = this.decodeLineStringCoords(lineStrCoord);
        l = new LineString(coords[0], coords[1]);
        lineStrings[i] = l;
      }

      geom = new MultiLineString(lineStrings);
    } else if (object.get("type").equals("LineString")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      double[][] coords = this.decodeLineStringCoords(coordinates);
      geom = new LineString(coords[0], coords[1]);
    } else if (object.get("type").equals("Point")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1));
    } else if (object.get("type").equals("Polygon")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      double[][] coords = this.decodeLineStringCoords(coordinates);
      geom = new Polygon(coords[0], coords[1]);
    }

    return geom;
  }
  public void initTab(String result) {
    tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
    try {
      JSONObject jsonObj = new JSONObject(result);
      JSONArray jsonArraySuccess = jsonObj.getJSONArray("Success");
      JSONArray jsonArrayFail = jsonObj.getJSONArray("Fail");
      int totalBooksBorrow = jsonArraySuccess.length() + jsonArrayFail.length();

      Bundle success = new Bundle();
      success.putString("Json", jsonArraySuccess.toString());
      success.putInt("totalBooksBorrow", totalBooksBorrow);

      Bundle fail = new Bundle();
      fail.putString("Json", jsonArrayFail.toString());
      fail.putInt("totalBooksBorrow", totalBooksBorrow);

      tabHost.addTab(
          tabHost.newTabSpec("Success").setIndicator("Success"),
          SuccessBorrowBookFragment.class,
          success);
      tabHost.addTab(
          tabHost.newTabSpec("Fail").setIndicator("Fail"), FailBorrowBookFragment.class, fail);

      tabHost.setOnTabChangedListener(
          new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
              /*Toast.makeText(ShowBorrowBooksResultActivity.this, "Tab Changed", Toast.LENGTH_SHORT).show();*/
            }
          });
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  private <T extends ReviewRequestBase> T fillReviewRequestBase(
      T reviewRequest, JSONObject jsonReviewRequest) throws JSONException {

    reviewRequest.setId(jsonReviewRequest.getInt("id"));
    reviewRequest.setSummary(jsonReviewRequest.getString("summary"));
    reviewRequest.setTestingDone(jsonReviewRequest.getString("testing_done"));
    reviewRequest.setDescription(jsonReviewRequest.getString("description"));
    reviewRequest.setPublic(jsonReviewRequest.getBoolean("public"));
    reviewRequest.setBranch(jsonReviewRequest.getString("branch"));

    // bugs
    reviewRequest.setBugsClosed(readStringArray(jsonReviewRequest, "bugs_closed"));

    // target people
    JSONArray jsonTargetPeople = jsonReviewRequest.getJSONArray("target_people");
    List<String> targetPeople = new ArrayList<String>();
    for (int j = 0; j < jsonTargetPeople.length(); j++)
      targetPeople.add(jsonTargetPeople.getJSONObject(j).getString("title"));
    reviewRequest.setTargetPeople(targetPeople);

    // target groups
    JSONArray jsonTargetGroups = jsonReviewRequest.getJSONArray("target_groups");
    List<String> targetGroups = new ArrayList<String>();
    for (int j = 0; j < jsonTargetGroups.length(); j++)
      targetGroups.add(jsonTargetGroups.getJSONObject(j).getString("title"));
    reviewRequest.setTargetGroups(targetGroups);

    return reviewRequest;
  }
 public void testMessageWithFireEvent() throws IOException, JSONException {
   StringWriter stringWriter = new StringWriter();
   PrintWriter printWriter = new PrintWriter(stringWriter);
   ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
   Display display = new Display();
   Shell shell = new Shell(display);
   Button button = new Button(shell, SWT.PUSH);
   writer.addFireEventPayload(WidgetUtil.getId(button), "selection");
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
   String actualEvent = payload.getString(IProtocolConstants.KEY_EVENT);
   assertEquals("selection", actualEvent);
   writer.addFireEventPayload(WidgetUtil.getId(button), "focus");
   writer.finish();
   actual = stringWriter.getBuffer().toString();
   message = new JSONObject(actual);
   widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   widgetObject = widgetArray.getJSONObject(1);
   type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type);
   actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
   actualEvent = payload.getString(IProtocolConstants.KEY_EVENT);
   assertEquals("focus", actualEvent);
 }
  private ArrayList<ContentValues> jsonParser(String jsonString) {
    ArrayList<ContentValues> list_deviceAttributes = new ArrayList<ContentValues>();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      JSONArray jsonArray = jsonObject.getJSONArray("deviceList");

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

        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
        if (jsonObject1.getString("pid").equals(pID)) {

          JSONArray deviceAttributes = jsonObject1.getJSONArray("deviceAttributes");
          for (int j = 0; j < deviceAttributes.length(); j++) {

            JSONObject jsonObject_deviceAttributes;
            jsonObject_deviceAttributes = deviceAttributes.getJSONObject(j);
            ContentValues cv1 = putContentValues("deviceAttributes", jsonObject_deviceAttributes);
            list_deviceAttributes.add(cv1);
          }
        }
      }

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

      return list_deviceAttributes;
    }
  }
 /**
  * 从jsonarray中获取产品列表信息
  *
  * @param jsonArray
  * @throws Exception
  */
 private void getProductList(JSONArray jsonArray) throws Exception {
   for (int i = 0; i < jsonArray.length(); i++) {
     Products products = new Products();
     JSONObject o = (JSONObject) jsonArray.get(i);
     JSONArray cidArrayJson = o.getJSONArray("cids");
     JSONArray cidArrayProImg = o.getJSONArray("proImages");
     JSONArray playableArray = o.getJSONArray("playables");
     products.count = o.getInt("count");
     products.findTime = o.getString("findtime");
     products.showTime = o.getString("showtime");
     for (int k = 0; k < cidArrayJson.length(); k++) {
       String cid = cidArrayJson.getString(k);
       LogPrint.Print("lybjson", "cid =" + cid); //
       products.arrcid.add(cid);
     }
     for (int k = 0; k < cidArrayProImg.length(); k++) {
       String proImg = cidArrayProImg.getString(k);
       LogPrint.Print("lybjson", "proImg = " + proImg); //
       products.arrProImg.add(proImg);
     }
     for (int k = 0; k < playableArray.length(); k++) {
       int playable = playableArray.getInt(k);
       products.arrPlayable.add(playable);
     }
     LogPrint.Print("lyb", "arrCommodity size = " + products.arrProImg.size());
     productItem.arrProducts.add(products);
   }
 }
Example #24
0
  public static Listing fromJSON(JSONObject jsonObj) {
    Listing biz = new Listing(jsonObj);
    try {
      biz.id = jsonObj.getString("id");
      biz.title = jsonObj.getString("dtitle");
      biz.street = jsonObj.getString("addr");
      biz.city = jsonObj.getString("city");
      biz.state = jsonObj.getString("state");
      biz.rating = jsonObj.getString("rating");
      biz.phone = jsonObj.getString("phone");
      biz.lat = jsonObj.getString("lat");
      biz.lon = jsonObj.getString("lon");

      // reviews..
      JSONObject reviewObj = biz.getJSONObject("reviews");
      if (reviewObj != null && reviewObj.getInt("count") > 0) {
        biz.reviews = Review.fromJSON(reviewObj.getJSONArray("review"));
      } else {
        biz.reviews = new ArrayList<Review>();
      }

      // Image
      JSONObject imgObj = biz.getJSONObject("fullsize_photos");
      if (imgObj.getInt("count") > 0) {
        biz.imageUrl = imgObj.getJSONArray("content").getJSONObject(0).getString("url");
      } else {
        biz.imageUrl = null;
      }
    } catch (JSONException e) {
      Log.d("pinank", e.getMessage());
      return null;
    }

    return biz;
  }
  @Override
  public int parse(String s) {

    JSONObject jObject = null;
    if (!isEmpty(s)) {
      try {
        jsonErrCode = ItvEngine.EVENT_OK;
        jObject = new JSONObject(s);
        if (jObject.getInt("errorcode") == jsonErrCode && jObject.has(DataSet.currentDate)) {
          JSONObject time = jObject.getJSONObject(DataSet.currentDate);
          JSONObject duration = time.getJSONObject(String.valueOf(DataSet.currentDuration));
          JSONArray array2 = jObject.getJSONArray("category");
          DataSet.currentTvChannels.clear();
          for (int i = 0; i < array2.length(); i++) {
            JSONObject categoryObject = array2.getJSONObject(i);
            Category category = new Category();
            category.id = categoryObject.getInt("id");
            category.name = categoryObject.getString("name");
            parseData(duration.getJSONArray(category.name), category);
          }

        } else {
          jsonErrCode = ItvEngine.EVENT_ERROR;
        }
      } catch (Exception e) {
        jsonErrCode = ItvEngine.EVENT_ERROR;
        e.printStackTrace();
      }
    }
    return jsonErrCode;
  }
  /**
   * Build a new end user instance from a JSONObject description
   *
   * @param jsonObject the JSONObject description
   */
  public AppsgateEndUser(JSONObject jsonObject) {

    this.instanciationService = Executors.newScheduledThreadPool(1);

    try {
      this.id = jsonObject.getString("id");
      this.hashPSWD = jsonObject.getString("hashPSWD");
      this.lastName = jsonObject.getString("lastName");
      this.firstName = jsonObject.getString("firstName");
      this.role = jsonObject.getString("role");

      JSONArray devices = jsonObject.getJSONArray("devices");
      int size = devices.length();
      int i = 0;
      while (i < size) {
        deviceOwnedList.add(devices.getString(i));
        i++;
      }

      // Create thread that take the account list in parameter and instanciate all account
      // TODO Schedule instanciation to avoid dependency collision
      instanciationService.schedule(
          new accountInstanciation(jsonObject.getJSONArray("accounts")), 15, TimeUnit.SECONDS);

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
    protected void onPostExecute(String response) {

      // Parse the response
      try {
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject != null) {
          JSONArray array = jsonObject.getJSONArray("data");
          JSONObject item = array.getJSONObject(0);
          String views = item.getJSONArray("values").getJSONObject(0).getString("value");
          selectedPost.setViews(Integer.parseInt(views));
          Log.d("facebook##", "views: " + views);
        }
        // show detail dialog
        new AlertDialog.Builder(PostListActivity.this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle("Post Detail")
            .setMessage(selectedPost.toString())
            .setPositiveButton(
                android.R.string.yes,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                  }
                })
            .show();

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
Example #28
0
 public static void setNetChannelList(ResponseInfo<String> info, List<NetMusicEntry> mList) {
   try {
     JSONObject object = new JSONObject(info.result);
     JSONArray array1 = object.getJSONArray("result");
     JSONObject object1 = array1.getJSONObject(0);
     JSONArray array = object1.getJSONArray(NetMusicEntry.CHANNELLIST);
     for (int i = 0; i < array.length(); i++) {
       JSONObject obj = array.getJSONObject(i);
       NetMusicEntry entry = new NetMusicEntry();
       try {
         entry.setName(obj.getString(NetMusicEntry.NAME));
       } catch (Exception e) {
       }
       try {
         entry.setThumb(obj.getString(NetMusicEntry.THUMB));
       } catch (Exception e) {
       }
       try {
         entry.setCh_name(obj.getString(NetMusicEntry.CH_NAME));
       } catch (Exception e) {
       }
       mList.add(entry);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_stories_view, container, false);
    getActivity().setTitle(getResources().getString(R.string.title_activity_news_home_screen));

    swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    swipeLayout.setOnRefreshListener(this);

    TextView noTopicsText = (TextView) rootView.findViewById(R.id.no_topics_textview);
    user = ValuesAndUtil.getInstance().loadUserData(getActivity().getApplicationContext());

    boolean hasTopics = false;
    try {
      hasTopics = user.has("topics") && user.getJSONArray("topics").length() > 0;
    } catch (JSONException e) {
      e.printStackTrace();
    }
    Log.d("SVF", "Has topics = " + hasTopics);
    if (!hasTopics) {
      noTopicsText.setText(getString(R.string.no_topics_available));
      swipeLayout.setVisibility(View.INVISIBLE);
    } else {
      Log.d("SVF", "Topics were not null");
      swipeLayout.setVisibility(View.VISIBLE);
      try {
        topics = user.getJSONArray("topics");
        setUpList(rootView, topics);
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return rootView;
  }
Example #30
0
 /** 緩存靜態數據中圖片的工具方法 */
 public static void fetchImg() {
   fetchCheck = true;
   if (SuspensionButton.mStrMsgBus == null || SuspensionButton.mStrMsgBus.equals("")) return;
   String result = SuspensionButton.mStrMsgBus;
   try {
     JSONObject jObject = new JSONObject(result);
     JSONArray jBannerArray = jObject.getJSONArray("banners");
     for (int i = 0; i < jBannerArray.length(); i++) {
       JSONObject jObjectI = jBannerArray.getJSONObject(i);
       String imgUrl = jObjectI.optString("img");
       new AsyncFetch().execute(imgUrl);
     }
     JSONArray jTaskArray = jObject.getJSONArray("tasks");
     for (int i = 0; i < jTaskArray.length(); i++) {
       JSONObject jObjectI = jTaskArray.getJSONObject(i);
       String imgUrl = jObjectI.optString("img");
       new AsyncFetch().execute(imgUrl);
     }
     JSONArray jInfoArray = jObject.getJSONArray("infos");
     for (int i = 0; i < jInfoArray.length(); i++) {
       JSONObject jObjectI = jInfoArray.getJSONObject(i);
       String imgUrl = jObjectI.optString("img");
       new AsyncFetch().execute(imgUrl);
     }
   } catch (Exception e) {
     Log.d("AsyncFetchERROR", "fetchImg");
   }
 }