Java Code Examples for org.json.JSONArray#optInt()

The following examples show how to use org.json.JSONArray#optInt() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ITeslaRules.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
public static void processTreeNode(JSONObject node, JSONArray inputs, String currentCondition, List<String> trueConditions, JSONObject stats, int trueIdx) {
    if ("thresholdTest".equals(node.optString("type"))) {
        int inputIdx = node.optInt("inputIndex");
        // conditional node
        String trueCondition = "("+inputs.opt(inputIdx)+" < "+node.optDouble("threshold")+")";
        String falseCondition = "("+inputs.opt(inputIdx)+" >= "+node.optDouble("threshold")+")";
        processTreeNode(node.optJSONObject("trueChild"), inputs, (currentCondition==null||currentCondition.length()==0)?trueCondition:(currentCondition+" and "+trueCondition), trueConditions, stats, trueIdx);
        processTreeNode(node.optJSONObject("falseChild"), inputs, (currentCondition==null||currentCondition.length()==0)?falseCondition:(currentCondition+" and "+falseCondition), trueConditions, stats, trueIdx);
    } else {
        String nodeIdx = node.optString("id");
        JSONArray nodeValues = stats.optJSONObject(nodeIdx).optJSONArray("counts");
        double purity = nodeValues.optInt(trueIdx) / (double)stats.optJSONObject(nodeIdx).optInt("count");
        if (purity > 0.95 && node.optBoolean("value")) {
            trueConditions.add(currentCondition == null ? "true" : currentCondition);
        }
    }
}
 
Example 2
Source File: Utility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static int[] parseVersionSpec(JSONArray versionsJSON) {
    // Null signifies no overrides to the min-version as specified by the SDK.
    // An empty array would basically turn off the dialog (i.e no supported versions), so
    // DON'T default to that.
    int[] versionSpec = null;
    if (versionsJSON != null) {
        int numVersions = versionsJSON.length();
        versionSpec = new int[numVersions];
        for (int i = 0; i < numVersions; i++) {
            // See if the version was stored directly as an Integer
            int version = versionsJSON.optInt(i, NativeProtocol.NO_PROTOCOL_AVAILABLE);
            if (version == NativeProtocol.NO_PROTOCOL_AVAILABLE) {
                // If not, then see if it was stored as a string that can be parsed out.
                // If even that fails, then we will leave it as NO_PROTOCOL_AVAILABLE
                String versionString = versionsJSON.optString(i);
                if (!isNullOrEmpty(versionString)) {
                    try {
                        version = Integer.parseInt(versionString);
                    } catch (NumberFormatException nfe) {
                        logd(LOG_TAG, nfe);
                        version = NativeProtocol.NO_PROTOCOL_AVAILABLE;
                    }
                }
            }

            versionSpec[i] = version;
        }
    }

    return versionSpec;
}
 
Example 3
Source File: BackgroundServicePluginLogic.java    From cbsp with MIT License 5 votes vote down vote up
public ExecuteResult enableTimer(JSONArray data)
{
	ExecuteResult result = null;

	int milliseconds = data.optInt(1, 60000);
	try {
		mApi.enableTimer(milliseconds);
		result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
	} catch (RemoteException ex) {
		Log.d(LOCALTAG, "enableTimer failed", ex);
		result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
	}

	return result;
}
 
Example 4
Source File: ParseUtils.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Parse int array from JSONObject with given name.
 *
 * @param from int JSON array like this one {@code {11, 34, 42}}
 */
public static int[] parseIntArray(JSONArray from) {
    int[] result = new int[from.length()];
    for (int i = 0; i < result.length; i++) {
        result[i] = from.optInt(i);
    }
    return result;
}
 
Example 5
Source File: VKApiChat.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a Chat instance from JSONObject.
 */
public VKApiChat parse(JSONObject source) {
    id = source.optInt("id");
    type = source.optString("type");
    title = source.optString("title");
    admin_id = source.optInt("admin_id");
    JSONArray users = source.optJSONArray("users");
    if(users != null) {
        this.users = new int[users.length()];
        for(int i = 0; i < this.users.length; i++) {
            this.users[i] = users.optInt(i);
        }
    }
    return this;
}
 
Example 6
Source File: Bundle.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public int[] getIntArray(String key) {
    try {
        JSONArray array = data.getJSONArray(key);

        int length = array.length();
        int[] result = new int[length];
        for (int i = 0; i < length; i++) {
            result[i] = array.optInt(i);
        }
        return result;
    } catch (JSONException e) {
        return new int[0];
    }
}
 
Example 7
Source File: LocalNotification.java    From showCaseCordova with Apache License 2.0 5 votes vote down vote up
/**
 * Clear multiple local notifications without canceling them.
 *
 * @param ids
 *      Set of local notification IDs
 */
private void clear(JSONArray ids){
    for (int i = 0; i < ids.length(); i++) {
        int id = ids.optInt(i, 0);

        Notification notification =
                getNotificationMgr().clear(id);

        if (notification == null)
            continue;

        fireEvent("clear", notification);
    }
}
 
Example 8
Source File: LocalNotification.java    From showCaseCordova with Apache License 2.0 5 votes vote down vote up
/**
 * Cancel multiple local notifications.
 *
 * @param ids
 *      Set of local notification IDs
 */
private void cancel (JSONArray ids) {
    for (int i = 0; i < ids.length(); i++) {
        int id = ids.optInt(i, 0);

        Notification notification =
                getNotificationMgr().cancel(id);

        if (notification == null)
            continue;

        fireEvent("cancel", notification);
    }
}
 
Example 9
Source File: JsonParser.java    From SprintNBA with Apache License 2.0 5 votes vote down vote up
public static TeamsRank parseTeamsRank(String jsonStr) {
    TeamsRank rank = new TeamsRank();
    String dataStr = JsonParser.parseBase(rank, jsonStr);
    rank.east = new ArrayList<>();
    rank.west = new ArrayList<>();
    try {
        JSONArray jsonArray = new JSONArray(dataStr);
        for (int i = 0; i < jsonArray.length(); i++) {
            org.json.JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
            String title = item.getString("title");
            JSONArray teamsArray = item.optJSONArray("rows");
            for (int j = 0; j < teamsArray.length(); j++) {
                JSONArray teamsInfo = teamsArray.getJSONArray(j);
                Gson gson = new Gson();
                TeamsRank.TeamBean bean = gson.fromJson(teamsInfo.getString(0), TeamsRank.TeamBean.class);
                bean.win = teamsInfo.optInt(1);
                bean.lose = teamsInfo.optInt(2);
                bean.rate = teamsInfo.optString(3);
                bean.difference = teamsInfo.optString(4);
                if (title.equals("东部联盟")) {
                    rank.east.add(bean);
                } else {
                    rank.west.add(bean);
                }
            }
        }
        return rank;
    } catch (Exception e) {
        LogUtils.e(e.toString());
    }
    return null;
}
 
Example 10
Source File: JsonUtil.java    From quickhybrid-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 解析JSONArray 获取数组 例如:["1",2,true,"4"]
 *
 * @param jsonArray 数据源
 * @param array     返回值
 * @return
 */
public static int[] parseJSONArray(JSONArray jsonArray, int[] array) {
    if (jsonArray != null) {
        try {
            array = new int[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                array[i] = jsonArray.optInt(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return array;
}
 
Example 11
Source File: FacebookRequestErrorClassification.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static Map<Integer, Set<Integer>> parseJSONDefinition(JSONObject definition) {
    JSONArray itemsArray = definition.optJSONArray("items");
    if (itemsArray.length() == 0) {
        return null;
    }

    Map<Integer, Set<Integer>> items = new HashMap<>();
    for (int i = 0; i < itemsArray.length(); i++) {
        JSONObject item = itemsArray.optJSONObject(i);
        if (item == null) {
            continue;
        }
        int code = item.optInt("code");
        if (code == 0) {
            continue;
        }
        Set<Integer> subcodes = null;
        JSONArray subcodesArray = item.optJSONArray("subcodes");
        if (subcodesArray != null && subcodesArray.length() > 0) {
            subcodes = new HashSet<>();
            for (int j = 0; j < subcodesArray.length(); j++) {
                int subCode = subcodesArray.optInt(j);
                if (subCode != 0) {
                    subcodes.add(subCode);
                }
            }
        }
        items.put(code, subcodes);
    }
    return items;
}
 
Example 12
Source File: InputConverter.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
private int[] convertColorVector(@Nullable JSONObject colorVector, int[] defaultValue) {
  if (colorVector != null && colorVector.has("colorVector")) {
    JSONArray cv = colorVector.optJSONArray("colorVector");
    int[] vector = new int[cv != null ? cv.length() : 0];

    for (int i = 0; i < vector.length; i++) {
      vector[i] = cv.optInt(i);
    }

    return vector;
  }

  return defaultValue;
}
 
Example 13
Source File: SpeechRecognition.java    From cordova-plugin-speechrecognition with MIT License 4 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
  this.callbackContext = callbackContext;

  Log.d(LOG_TAG, "execute() action " + action);

  try {
    if (IS_RECOGNITION_AVAILABLE.equals(action)) {
      boolean available = isRecognitionAvailable();
      PluginResult result = new PluginResult(PluginResult.Status.OK, available);
      callbackContext.sendPluginResult(result);
      return true;
    }

    if (START_LISTENING.equals(action)) {
      if (!isRecognitionAvailable()) {
        callbackContext.error(NOT_AVAILABLE);
        return true;
      }
      if (!audioPermissionGranted(RECORD_AUDIO_PERMISSION)) {
        callbackContext.error(MISSING_PERMISSION);
        return true;
      }

      String lang = args.optString(0);
      if (lang == null || lang.isEmpty() || lang.equals("null")) {
        lang = Locale.getDefault().toString();
      }

      int matches = args.optInt(1, MAX_RESULTS);

      String prompt = args.optString(2);
      if (prompt == null || prompt.isEmpty() || prompt.equals("null")) {
        prompt = null;
      }

      mLastPartialResults = new JSONArray();
      Boolean showPartial = args.optBoolean(3, false);
      Boolean showPopup = args.optBoolean(4, true);
      startListening(lang, matches, prompt,showPartial, showPopup);

      return true;
    }

    if (STOP_LISTENING.equals(action)) {
      final CallbackContext callbackContextStop = this.callbackContext;
      view.post(new Runnable() {
        @Override
        public void run() {
          if(recognizer != null) {
            recognizer.stopListening();
          }
          callbackContextStop.success();
        }
      });
      return true;
    }

    if (GET_SUPPORTED_LANGUAGES.equals(action)) {
      getSupportedLanguages();
      return true;
    }

    if (HAS_PERMISSION.equals(action)) {
      hasAudioPermission();
      return true;
    }

    if (REQUEST_PERMISSION.equals(action)) {
      requestAudioPermission();
      return true;
    }

  } catch (Exception e) {
    e.printStackTrace();
    callbackContext.error(e.getMessage());
  }

  return false;
}
 
Example 14
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected int getInt(JSONArray array, int index) {
    return array.optInt(index);
}
 
Example 15
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected int getInt(JSONArray array, int index) {
    return array.optInt(index);
}
 
Example 16
Source File: SourceMapConsumerV1.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses the first section of the source map file that has character
 * mappings.
 * @param parser The parser to use
 * @param lineCount The number of lines in the generated JS
 * @return The max id found in the file
 */
private int parseCharacterMap(
    ParseState parser, int lineCount,
    ImmutableList.Builder<ImmutableList<LineFragment>> characterMapBuilder)
    throws SourceMapParseException, JSONException {
  int maxID = -1;
  // [0,,,,,,1,2]
  for (int i = 0; i < lineCount; ++i) {
    String currentLine = parser.readLine();

    // Blank lines are allowed in the spec to indicate no mapping
    // information for the line.
    if (currentLine.isEmpty()) {
      continue;
    }

    ImmutableList.Builder<LineFragment> fragmentList =
        ImmutableList.builder();
    // We need the start index to initialize this, needs to be done in the
    // loop.
    LineFragment myLineFragment = null;

    JSONArray charArray = new JSONArray(currentLine);
    int numOffsets = charArray.length();
    int lastID = -1;
    int startID = Integer.MIN_VALUE;
    List<Byte> currentOffsets = Lists.newArrayList();
    for (int j = 0; j < charArray.length(); ++j) {
      // Keep track of the current mappingID, if the next element in the
      // array is empty we reuse the existing mappingID for the column.
      int mappingID = lastID;
      if (!charArray.isNull(j)) {
        mappingID = charArray.optInt(j);
        if (mappingID > maxID) {
          maxID = mappingID;
        }
      }

      if (startID == Integer.MIN_VALUE) {
        startID = mappingID;
      } else {
        // If the difference is bigger than a byte we need to keep track of
        // a new line fragment with a new start value.
        if (mappingID - lastID > Byte.MAX_VALUE
            || mappingID - lastID < Byte.MIN_VALUE) {
          myLineFragment = new LineFragment(
              startID, Bytes.toArray(currentOffsets));
          currentOffsets.clear();
          // Start a new section.
          fragmentList.add(myLineFragment);
          startID = mappingID;
        } else {
          currentOffsets.add((byte) (mappingID - lastID));
        }
      }

      lastID = mappingID;
    }
    if (startID != Integer.MIN_VALUE) {
      myLineFragment = new LineFragment(
          startID, Bytes.toArray(currentOffsets));
      fragmentList.add(myLineFragment);
    }
    characterMapBuilder.add(fragmentList.build());
  }
  return maxID;
}
 
Example 17
Source File: JsonHelper.java    From remixed-dungeon with GNU General Public License v3.0 4 votes vote down vote up
public static Animation readAnimation(JSONObject root, String animKind, TextureFilm film, int offset) throws JSONException {
	JSONObject jsonAnim = root.getJSONObject(animKind);

	Animation anim = new Animation(jsonAnim.getInt("fps"), jsonAnim.getBoolean("looped"));

	JSONArray jsonFrames = jsonAnim.getJSONArray("frames");

	List<Integer> framesSeq = new ArrayList<>(jsonFrames.length());

	int nextFrame;

	for (int i = 0; (nextFrame = jsonFrames.optInt(i, -1)) != -1; ++i) {
		framesSeq.add(nextFrame);
	}

	anim.frames(film, framesSeq, offset);

	return anim;
}
 
Example 18
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected int getInt(JSONArray array, int index) {
    return array.optInt(index);
}