@@ -247,6 +247,31 @@ public double getDouble(int index) throws JSONException {
247247 }
248248 }
249249
250+ /**
251+ * Get the enum value associated with an index.
252+ *
253+ * @param clazz
254+ * The type of enum to retrieve.
255+ * @param index
256+ * The index must be between 0 and length() - 1.
257+ * @return The enum value.
258+ * @throws JSONException
259+ * if the key is not found or if the value cannot be converted
260+ * to an enum.
261+ */
262+ public <E extends Enum <E >> E getEnum (Class <E > clazz , int index ) throws JSONException {
263+ E val = optEnum (clazz , index );
264+ if (val ==null ) {
265+ // JSONException should really take a throwable argument.
266+ // If it did, I would re-implement this with the Enum.valueOf
267+ // method and place any thrown exception in the JSONException
268+ throw new JSONException ("JSONObject[" + JSONObject .quote (Integer .toString (index ))
269+ + "] is not an enum of type " + JSONObject .quote (clazz .getSimpleName ())
270+ + "." );
271+ }
272+ return val ;
273+ }
274+
250275 /**
251276 * Get the BigDecimal value associated with an index.
252277 *
@@ -531,6 +556,50 @@ public int optInt(int index, int defaultValue) {
531556 }
532557 }
533558
559+ /**
560+ * Get the enum value associated with a key.
561+ *
562+ * @param clazz
563+ * The type of enum to retrieve.
564+ * @param index
565+ * The index must be between 0 and length() - 1.
566+ * @return The enum value or null if not found
567+ */
568+ public <E extends Enum <E >> E optEnum (Class <E > clazz , int index ) {
569+ return this .optEnum (clazz , index , null );
570+ }
571+
572+ /**
573+ * Get the enum value associated with a key.
574+ *
575+ * @param clazz
576+ * The type of enum to retrieve.
577+ * @param index
578+ * The index must be between 0 and length() - 1.
579+ * @param defaultValue
580+ * The default in case the value is not found
581+ * @return The enum value or defaultValue if the value is not found or
582+ * cannot be assigned to clazz
583+ */
584+ public <E extends Enum <E >> E optEnum (Class <E > clazz , int index , E defaultValue ) {
585+ try {
586+ Object val = this .opt (index );
587+ if (JSONObject .NULL .equals (val )) {
588+ return defaultValue ;
589+ }
590+ if (clazz .isAssignableFrom (val .getClass ())) {
591+ // we just checked it!
592+ @ SuppressWarnings ("unchecked" )
593+ E myE = (E ) val ;
594+ return myE ;
595+ }
596+ return Enum .valueOf (clazz , val .toString ());
597+ } catch (IllegalArgumentException | NullPointerException e ) {
598+ return defaultValue ;
599+ }
600+ }
601+
602+
534603 /**
535604 * Get the optional BigInteger value associated with an index. The
536605 * defaultValue is returned if there is no value for the index, or if the
0 commit comments