|
| 1 | +package com.telerik.pushplugin; |
| 2 | + |
| 3 | + |
| 4 | +import org.json.JSONArray; |
| 5 | +import org.json.JSONObject; |
| 6 | +import java.util.Collection; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | + |
| 10 | +public class JsonObjectExtended extends JSONObject{ |
| 11 | + //Overwrite for the method wrap as it is only available in Api Level 19+ and this ensures |
| 12 | + //it will work on lower level deployments |
| 13 | + |
| 14 | + /** |
| 15 | + * Wraps the given object if necessary. |
| 16 | + * |
| 17 | + * <p>If the object is null or , returns {@link #NULL}. |
| 18 | + * If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary. |
| 19 | + * If the object is {@code NULL}, no wrapping is necessary. |
| 20 | + * If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}. |
| 21 | + * If the object is a {@code Map}, returns an equivalent {@code JSONObject}. |
| 22 | + * If the object is a primitive wrapper type or {@code String}, returns the object. |
| 23 | + * Otherwise if the object is from a {@code java} package, returns the result of {@code toString}. |
| 24 | + * If wrapping fails, returns null. |
| 25 | + */ |
| 26 | + public static Object wrap(Object o) { |
| 27 | + if (o == null) { |
| 28 | + return NULL; |
| 29 | + } |
| 30 | + if (o instanceof JSONArray || o instanceof JSONObject) { |
| 31 | + return o; |
| 32 | + } |
| 33 | + if (o.equals(NULL)) { |
| 34 | + return o; |
| 35 | + } |
| 36 | + try { |
| 37 | + if (o instanceof Collection) { |
| 38 | + return new JSONArray((Collection) o); |
| 39 | + } else if (o.getClass().isArray()) { |
| 40 | + return new JSONArray(o); |
| 41 | + } |
| 42 | + if (o instanceof Map) { |
| 43 | + return new JSONObject((Map) o); |
| 44 | + } |
| 45 | + if (o instanceof Boolean || |
| 46 | + o instanceof Byte || |
| 47 | + o instanceof Character || |
| 48 | + o instanceof Double || |
| 49 | + o instanceof Float || |
| 50 | + o instanceof Integer || |
| 51 | + o instanceof Long || |
| 52 | + o instanceof Short || |
| 53 | + o instanceof String) { |
| 54 | + return o; |
| 55 | + } |
| 56 | + if (o.getClass().getPackage().getName().startsWith("java.")) { |
| 57 | + return o.toString(); |
| 58 | + } |
| 59 | + } catch (Exception ignored) { |
| 60 | + } |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments