|
| 1 | +package com.wearconnectivity; |
| 2 | + |
| 3 | +import java.util.Iterator; |
| 4 | +import org.json.JSONArray; |
| 5 | +import org.json.JSONException; |
| 6 | +import org.json.JSONObject; |
| 7 | + |
| 8 | +public class JSONToWritableMap { |
| 9 | + |
| 10 | + /** |
| 11 | + * Parse JSONObject to ReadableMap |
| 12 | + * |
| 13 | + * @param obj The JSONObject to be parsed |
| 14 | + * @return readableMap from the JSONObject |
| 15 | + */ |
| 16 | + public static ReadableMap fromJSONObject(JSONObject obj) throws JSONException { |
| 17 | + WritableMap result = Arguments.createMap(); |
| 18 | + Iterator<String> keys = obj.keys(); |
| 19 | + |
| 20 | + while (keys.hasNext()) { |
| 21 | + String key = keys.next(); |
| 22 | + Object val = obj.get(key); |
| 23 | + if (val instanceof JSONObject) { |
| 24 | + result.putMap(key, fromJSONObject((JSONObject) val)); |
| 25 | + } else if (val instanceof JSONArray) { |
| 26 | + result.putArray(key, fromJSONArray((JSONArray) val)); |
| 27 | + } else if (val instanceof String) { |
| 28 | + result.putString(key, (String) val); |
| 29 | + } else if (val instanceof Boolean) { |
| 30 | + result.putBoolean(key, (Boolean) val); |
| 31 | + } else if (val instanceof Integer) { |
| 32 | + result.putInt(key, (Integer) val); |
| 33 | + } else if (val instanceof Double) { |
| 34 | + result.putDouble(key, (Double) val); |
| 35 | + } else if (val instanceof Long) { |
| 36 | + result.putInt(key, ((Long) val).intValue()); |
| 37 | + } else if (obj.isNull(key)) { |
| 38 | + result.putNull(key); |
| 39 | + } else { |
| 40 | + // Unknown value type. Will throw |
| 41 | + throw new JSONException("Unexpected value when parsing JSON object. key: " + key); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | + } |
| 47 | +} |
0 commit comments