I was working on the android integration of react-native-intercom today and found that I had to forward an arbitrary ReadableMap to Intercom as a normal Map fully unboxed. I quickly realized there was no way to transform the ReadableMap into a usable object without recursively deconstructing it by hand.
Ideally, it'd be nice to have the ability to say unwrap() or getObject().
My current approach is to use the ReadableMapKeySetIterator and go through each node recursively
private Map<String, Object> recursivelyDeconstructReadableMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Object> deconstructedMap = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
deconstructedMap.put(key, null);
break;
case Boolean:
deconstructedMap.put(key, readableMap.getBoolean(key));
break;
case Number:
deconstructedMap.put(key, readableMap.getDouble(key));
break;
case String:
deconstructedMap.put(key, readableMap.getString(key));
break;
case Map:
deconstructedMap.put(key, recursivelyDeconstructReadableMap(readableMap.getMap(key)));
break;
case Array:
deconstructedMap.put(key, recursivelyDeconstructReadableArray(readableMap.getArray(key)));
break;
default:
throw new IllegalArgumentException("Could not convert object with key: " + key + ".");
}
}
return deconstructedMap;
}
private List<Object> recursivelyDeconstructReadableArray(ReadableArray readableArray) {
List<Object> deconstructedList = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch(indexType) {
case Null:
deconstructedList.add(i, null);
break;
case Boolean:
deconstructedList.add(i, readableArray.getBoolean(i));
break;
case Number:
deconstructedList.add(i, readableArray.getDouble(i));
break;
case String:
deconstructedList.add(i, readableArray.getString(i));
break;
case Map:
deconstructedList.add(i, recursivelyDeconstructReadableMap(readableArray.getMap(i)));
break;
case Array:
deconstructedList.add(i, recursivelyDeconstructReadableArray(readableArray.getArray(i)));
break;
default:
throw new IllegalArgumentException("Could not convert object at index " + i + ".");
}
}
return deconstructedList;
}
This seems like a handy method that could exist on the ReadableMap and ReadableArray itself.
I was working on the android integration of react-native-intercom today and found that I had to forward an arbitrary
ReadableMaptoIntercomas a normalMapfully unboxed. I quickly realized there was no way to transform theReadableMapinto a usable object without recursively deconstructing it by hand.Ideally, it'd be nice to have the ability to say
unwrap()orgetObject().My current approach is to use the
ReadableMapKeySetIteratorand go through each node recursivelyThis seems like a handy method that could exist on the
ReadableMapandReadableArrayitself.