List of usage examples for org.json JSONArray length
public int length()
From source file:com.jsonstore.util.JSONStoreUtil.java
public static List<JSONObject> convertJSONArrayToJSONObjectList(JSONArray arr) { List<JSONObject> results = new LinkedList<JSONObject>(); if (arr != null) { for (int i = 0; i < arr.length(); i++) { try { results.add(arr.getJSONObject(i)); } catch (JSONException e) { //Do nothing. Ignore this entry }//from w w w. j a va2 s . c om } } return results; }
From source file:com.trellmor.berrytube.BerryTubeIOCallback.java
/** * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge, * java.lang.Object[])//from w w w. j av a 2 s .c om */ public void on(String event, IOAcknowledge ack, Object... args) { if (event.compareTo("chatMsg") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject jsonMsg = (JSONObject) args[0]; try { berryTube.getHandler() .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg")))); } catch (JSONException e) { Log.e(TAG, "chatMsg", e); } } else Log.w(TAG, "chatMsg message is not a JSONObject"); } else if (event.compareTo("setNick") == 0) { if (args.length >= 1 && args[0] instanceof String) { berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0])); } else Log.w(TAG, "setNick message is not a String"); } else if (event.compareTo("loginError") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject error = (JSONObject) args[0]; berryTube.getHandler() .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed"))); } } else if (event.compareTo("userJoin") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "userJoin", e); } } else Log.w(TAG, "userJoin message is not a JSONObject"); } else if (event.compareTo("newChatList") == 0) { berryTube.getHandler().post(berryTube.new UserResetTask()); if (args.length >= 1 && args[0] instanceof JSONArray) { JSONArray users = (JSONArray) args[0]; for (int i = 0; i < users.length(); i++) { JSONObject user = users.optJSONObject(i); if (user != null) { try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "newChatList", e); } } } } else Log.w(TAG, "newChatList message is not a JSONArray"); } else if (event.compareTo("userPart") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_PART)); } catch (JSONException e) { Log.e(TAG, "userPart", e); } } else Log.w(TAG, "userPart message is not a JSONObject"); } else if (event.compareTo("drinkCount") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject drinks = (JSONObject) args[0]; berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks"))); } } else if (event.compareTo("kicked") == 0) { berryTube.getHandler().post(berryTube.new KickedTask()); } else if (event.compareTo("newPoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; ChatMessage msg; // Send chat message for new poll try { msg = new ChatMessage(poll.getString("creator"), poll.getString("title"), ChatMessage.EMOTE_POLL, 0, 0, false, 1); berryTube.getHandler().post(berryTube.new ChatMsgTask(msg)); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } // Create new poll try { berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll))); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } } } else if (event.compareTo("updatePoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; try { JSONArray votes = poll.getJSONArray("votes"); int[] voteArray = new int[votes.length()]; for (int i = 0; i < votes.length(); i++) { voteArray[i] = votes.optInt(i, -1); } berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray)); } catch (JSONException e) { Log.e(TAG, "updatePoll", e); } } } else if (event.compareTo("clearPoll") == 0) { berryTube.getHandler().post(berryTube.new ClearPollTask()); } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject videoMsg = (JSONObject) args[0]; try { JSONObject video = videoMsg.getJSONObject("video"); String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8"); String id = video.getString("videoid"); String type = video.getString("videotype"); berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type)); } catch (JSONException | UnsupportedEncodingException e) { Log.w(TAG, e); } } } }
From source file:com.facebook.internal.BundleJSONConverterTest.java
@Test public void testSimpleValues() throws JSONException { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1st"); arrayList.add("2nd"); arrayList.add("third"); Bundle innerBundle1 = new Bundle(); innerBundle1.putInt("inner", 1); Bundle innerBundle2 = new Bundle(); innerBundle2.putString("inner", "2"); innerBundle2.putStringArray("deep list", new String[] { "7", "8" }); innerBundle1.putBundle("nested bundle", innerBundle2); Bundle b = new Bundle(); b.putBoolean("boolValue", true); b.putInt("intValue", 7); b.putLong("longValue", 5000000000l); b.putDouble("doubleValue", 3.14); b.putString("stringValue", "hello world"); b.putStringArray("stringArrayValue", new String[] { "first", "second" }); b.putStringArrayList("stringArrayListValue", arrayList); b.putBundle("nested", innerBundle1); JSONObject json = BundleJSONConverter.convertToJSON(b); assertNotNull(json);/*from w ww . j av a 2 s . co m*/ assertEquals(true, json.getBoolean("boolValue")); assertEquals(7, json.getInt("intValue")); assertEquals(5000000000l, json.getLong("longValue")); assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", json.getString("stringValue")); JSONArray jsonArray = json.getJSONArray("stringArrayValue"); assertEquals(2, jsonArray.length()); assertEquals("first", jsonArray.getString(0)); assertEquals("second", jsonArray.getString(1)); jsonArray = json.getJSONArray("stringArrayListValue"); assertEquals(3, jsonArray.length()); assertEquals("1st", jsonArray.getString(0)); assertEquals("2nd", jsonArray.getString(1)); assertEquals("third", jsonArray.getString(2)); JSONObject innerJson = json.getJSONObject("nested"); assertEquals(1, innerJson.getInt("inner")); innerJson = innerJson.getJSONObject("nested bundle"); assertEquals("2", innerJson.getString("inner")); jsonArray = innerJson.getJSONArray("deep list"); assertEquals(2, jsonArray.length()); assertEquals("7", jsonArray.getString(0)); assertEquals("8", jsonArray.getString(1)); Bundle finalBundle = BundleJSONConverter.convertToBundle(json); assertNotNull(finalBundle); assertEquals(true, finalBundle.getBoolean("boolValue")); assertEquals(7, finalBundle.getInt("intValue")); assertEquals(5000000000l, finalBundle.getLong("longValue")); assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", finalBundle.getString("stringValue")); List<String> stringList = finalBundle.getStringArrayList("stringArrayValue"); assertEquals(2, stringList.size()); assertEquals("first", stringList.get(0)); assertEquals("second", stringList.get(1)); stringList = finalBundle.getStringArrayList("stringArrayListValue"); assertEquals(3, stringList.size()); assertEquals("1st", stringList.get(0)); assertEquals("2nd", stringList.get(1)); assertEquals("third", stringList.get(2)); Bundle finalInnerBundle = finalBundle.getBundle("nested"); assertEquals(1, finalInnerBundle.getInt("inner")); finalBundle = finalInnerBundle.getBundle("nested bundle"); assertEquals("2", finalBundle.getString("inner")); stringList = finalBundle.getStringArrayList("deep list"); assertEquals(2, stringList.size()); assertEquals("7", stringList.get(0)); assertEquals("8", stringList.get(1)); }
From source file:salvatejero.cordova.liferay.LiferayPlugin.java
private void getObjectModel(final CallbackContext callbackContext, String className, String methodName, JSONArray values) throws Exception { JSONArray jsonArrayInstance = new JSONArray(); JSONObject jsonObjectInstance = new JSONObject(); JSONObjectAsyncTaskCallback callBackJSONObject = new JSONObjectAsyncTaskCallback() { @Override//from w w w . j a v a 2 s . co m public void onFailure(Exception arg0) { callbackContext.error(arg0.getMessage()); } @Override public void onSuccess(JSONObject arg0) { // TODO Auto-generated method stub PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, arg0); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }; JSONArrayAsyncTaskCallback callbackJSONArray = new JSONArrayAsyncTaskCallback() { @Override public void onFailure(Exception arg0) { callbackContext.error(arg0.getMessage()); } @Override public void onSuccess(JSONArray arg0) { PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, arg0); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }; Method methodToExecute = null; Object[] params = null; BaseService service = getService(className); if (service == null) { throw new LiferayPluginException("Service not implemented"); } Method[] methods = service.getClass().getMethods(); for (Method m : methods) { if (m.getName().toLowerCase().equals(methodName.toLowerCase())) { if (values.length() != m.getParameterTypes().length) { throw new LiferayPluginException("Number of params error for the method " + methodName); } params = getListOfParam(m, values); if (m.getReturnType().isInstance(jsonArrayInstance)) { session.setCallback(callbackJSONArray); } else if (m.getReturnType().isInstance(jsonObjectInstance)) { session.setCallback(callBackJSONObject); } else if (m.getReturnType().equals(Void.TYPE)) { callbackContext.success(); } methodToExecute = m; break; } } if (methodToExecute == null) { for (Method m : methods) { if (methodName.indexOf(m.getName().toLowerCase()) >= 0) { if (values.length() != m.getParameterTypes().length) { throw new LiferayPluginException("Number of params error for the method " + methodName); } params = getListOfParam(m, values); if (m.getReturnType().isInstance(jsonArrayInstance)) { session.setCallback(callbackJSONArray); } else if (m.getReturnType().isInstance(jsonObjectInstance)) { session.setCallback(callBackJSONObject); } else if (m.getReturnType().equals(Void.TYPE)) { callbackContext.success(); } methodToExecute = m; break; } } } if (methodToExecute == null) { throw new LiferayPluginException("Method " + methodName + "not found"); } try { methodToExecute.invoke(service, params); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new LiferayPluginException("Error invoking -- " + e.getMessage()); } }
From source file:salvatejero.cordova.liferay.LiferayPlugin.java
protected JSONObject getGuestGroupId(Session session) throws Exception { long groupId = -1; GroupService groupService = new GroupService(session); JSONArray groups = groupService.getUserSites(); for (int i = 0; i < groups.length(); i++) { JSONObject group = groups.getJSONObject(i); String name = group.getString("name"); if (!name.equals("Guest")) { continue; }/*from w w w.j av a 2s . c om*/ return group; } if (groupId == -1) { throw new Exception("Couldn't find Guest group."); } return null; }
From source file:game.Clue.ClueGameUI.java
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // TODO add your handling code here: //Move Button Pressed // check game-state to determine available moves //new JSONObject("{"players":[{"position":"0,3","name":null,"active":"true","cards":"MR GREEN,CANDLESTICK,BALLROOM","character":"scarlet"},{"position":"1,4","name":null,"active":"true","cards":"PROFESSOR PLUM,BILLARD ROOM,ROPE","character":"mustard"},{"position":"4,3","name":null,"active":"true","cards":"DINING ROOM,REVOLVER,WRENCH","character":"white"},{"position":"4,1","name":null,"active":"true","cards":"LIBRARY,COLONEL MUSTARD,STUDY","character":"green"},{"position":"3,0","name":null,"active":"true","cards":"MISS SCARLET,MRS PEACOCK,KNIFE","character":"peacock"},{"position":"1,0","name":null,"active":"true","cards":"HALL,CONSERVATORY,LOUNGE","character":"plum"}],"move_state":{"player":"scarlet","moves":[["[0,4, 0,2]","accusation"]]},"winner":null}"); try {// w w w .j a va2 s . c om JSONArray available_moves; //String available_moves; String[] available_moves_array; Object[] available_moves_object = null; available_moves = player_connection.currentgame_state.getJSONObject("move_state").getJSONArray("moves"); //available_moves_array = available_moves.split("]"); System.out.println(available_moves.length()); for (int i = 0; i < available_moves.length(); i++) { System.out.println(available_moves.get(i)); //available_moves_object[i] = } //String m = (String) JOptionPane.showInputDialog(this, "Where would you live to move?", "Select your move", JOptionPane.PLAIN_MESSAGE, null, available_moves_object, ""); } catch (JSONException ex) { Logger.getLogger(ClueGameUI.class.getName()).log(Level.SEVERE, null, ex); } //let user select which room ,from options presented, to move into //update server with new players location }
From source file:game.Clue.ClueGameUI.java
private void initializeMyHand() { //get player's hand from game state data JSONArray card_hand; String[] card_hand_object = null; try {//from ww w .jav a2 s. c om card_hand = player_connection.currentgame_state.getJSONArray("players") .getJSONObject(player_connection.game_slot).getJSONArray("cards"); for (int i = 0; i < card_hand.length(); i++) { card_hand_object[i] = card_hand.get(i).toString(); } mycard1.setText(card_hand_object[1]); //card 1 mycard2.setText(card_hand_object[2]); //card 2 mycard3.setText(card_hand_object[3]); //card 3 System.out.println(mycard1.getText()); System.out.println(mycard2.getText()); System.out.println(mycard3.getText()); } catch (JSONException ex) { Logger.getLogger(ClueGameUI.class.getName()).log(Level.SEVERE, null, ex); } // player.connection.currentgame_state. }
From source file:org.jabsorb.ng.serializer.impl.RawJSONArraySerializer.java
@Override public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException { // reprocess the raw json in order to fixup circular references and // duplicates final JSONArray jsonIn = (JSONArray) o; final JSONArray jsonOut = new JSONArray(); int i = 0;/*from ww w . j a va2 s . c o m*/ try { final int j = jsonIn.length(); for (i = 0; i < j; i++) { final Object json = ser.marshall(state, o, jsonIn.get(i), new Integer(i)); if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) { jsonOut.put(i, json); } else { // put a slot where the object would go, so it can be fixed // up properly in the fix up phase jsonOut.put(i, JSONObject.NULL); } } } catch (final MarshallException e) { throw new MarshallException("element " + i, e); } catch (final JSONException e) { throw new MarshallException("element " + i, e); } return jsonOut; }
From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java
/** * Gets the attribute which has the appended schema attributes and splits them * to add individual items in the provided set. * @param config Config of user entered entries * @param tempSchema Set which holds the schema attributes. *///from ww w . j av a 2 s . c o m private void addSchemaFromConfig(Map<String, String> config, Set<String> tempSchema) { String schemaValues = getJsonStringForSelectedAttributes(config); if (schemaValues != null && schemaValues.trim().length() != 0) { JSONArray arr; try { arr = new JSONArray(schemaValues); for (int i = 0; i < arr.length(); i++) { tempSchema.add(arr.getString(i)); } } catch (JSONException e) { LOG.warning("Did not get any selected attributes..."); } } LOG.fine("Selected attributes: " + tempSchema); }
From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java
/** * Returns the string that represents the selected attributes in a json * understandable way. //from w ww .j a v a2 s . co m * First tries to search if the json string is passed by the config. If it is * not found then we try to create the json string from original LDAP * configuration format. The original format is individual keys for * each value. * @return String json parsable string representation of the selected * attributes */ static String getJsonStringForSelectedAttributes(Map<String, String> config) { String schemaValue = config.get(ConfigName.SCHEMAVALUE.toString()); if (schemaValue == null || schemaValue.equals("[]")) { LOG.info("Trying to recover attributes from individual checkboxes"); StringBuffer schemaKey = new StringBuffer(); schemaKey.append(ConfigName.SCHEMA.toString()).append("_").append("\\d"); Pattern keyPattern = Pattern.compile(schemaKey.toString()); Set<String> configKeySet = config.keySet(); JSONArray arr = new JSONArray(); for (String configKey : configKeySet) { Matcher matcher = keyPattern.matcher(configKey); if (matcher.find()) { String schemaAttribute = config.get(configKey); if (schemaAttribute != null && schemaAttribute.trim().length() != 0) { arr.put(config.get(configKey)); } } } if (arr.length() != 0) { schemaValue = arr.toString(); } else { schemaValue = ""; } } LOG.info("The appended string for selected attributes is: " + schemaValue); return schemaValue; }