Skip to content

Commit 91107e3

Browse files
author
John J. Aylward
committed
Adds support to JSONObject wrap and write methods to explicitly handle Enums.
The new way enums are handled is to always place the actual enum in the JSONObject/JSONArray. When writing, we always write the actual "name" of the enum, so even with a toString override on the enum class, the value remains consistant and compatible with the optEnum/getEnum methods. The constructor JSONObject(Object) functions the same way as before when passing an enum and is consistent with other "value" types. For example, when creating a JSONObject with Long, Boolean, BigDecimal as the constructor parameter, the value will be treated as a "bean".
1 parent 4e8e24d commit 91107e3

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

JSONObject.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1708,6 +1708,9 @@ public static String valueToString(Object value) throws JSONException {
17081708
if (value.getClass().isArray()) {
17091709
return new JSONArray(value).toString();
17101710
}
1711+
if(value instanceof Enum<?>){
1712+
return quote(((Enum<?>)value).name());
1713+
}
17111714
return quote(value.toString());
17121715
}
17131716

@@ -1730,12 +1733,9 @@ public static Object wrap(Object object) {
17301733
}
17311734
if (object instanceof JSONObject || object instanceof JSONArray
17321735
|| NULL.equals(object) || object instanceof JSONString
1733-
|| object instanceof Byte || object instanceof Character
1734-
|| object instanceof Short || object instanceof Integer
1735-
|| object instanceof Long || object instanceof Boolean
1736-
|| object instanceof Float || object instanceof Double
1737-
|| object instanceof String || object instanceof BigInteger
1738-
|| object instanceof BigDecimal) {
1736+
|| object instanceof Number || object instanceof Character
1737+
|| object instanceof Boolean || object instanceof String
1738+
|| object instanceof Enum) {
17391739
return object;
17401740
}
17411741

@@ -1797,6 +1797,8 @@ static final Writer writeValue(Writer writer, Object value,
17971797
writer.write(numberToString((Number) value));
17981798
} else if (value instanceof Boolean) {
17991799
writer.write(value.toString());
1800+
} else if (value instanceof Enum<?>) {
1801+
writer.write(quote(((Enum<?>)value).name()));
18001802
} else if (value instanceof JSONString) {
18011803
Object o;
18021804
try {

0 commit comments

Comments
 (0)