Add toArrayList and toHashMap methods for ReadableArray and ReadableMap. Fixes #4655

Summary:Context #4658

I kept the original commit and author.

cc mkonicek
Closes https://github.com/facebook/react-native/pull/6639

Differential Revision: D3126336

Pulled By: mkonicek

fb-gh-sync-id: 5ae7b37f0eb1db355bb87076d621a405ff9c23c5
fbshipit-source-id: 5ae7b37f0eb1db355bb87076d621a405ff9c23c5
This commit is contained in:
Atticus White 2016-04-01 07:01:22 -07:00 committed by Facebook Github Bot 6
parent 31bb85a210
commit dc3836a9d3
2 changed files with 64 additions and 0 deletions

View File

@ -13,6 +13,8 @@ import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader;
import java.util.ArrayList;
/**
* Implementation of a NativeArray that allows read-only access to its members. This will generally
* be constructed and filled in native code so you shouldn't construct one yourself.
@ -46,4 +48,34 @@ public class ReadableNativeArray extends NativeArray implements ReadableArray {
public native ReadableNativeMap getMap(int index);
@Override
public native ReadableType getType(int index);
public ArrayList<Object> toArrayList() {
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < this.size(); i++) {
switch (getType(i)) {
case Null:
arrayList.add(null);
break;
case Boolean:
arrayList.add(getBoolean(i));
break;
case Number:
arrayList.add(getDouble(i));
break;
case String:
arrayList.add(getString(i));
break;
case Map:
arrayList.add(getMap(i).toHashMap());
break;
case Array:
arrayList.add(getArray(i).toArrayList());
break;
default:
throw new IllegalArgumentException("Could not convert object at index: " + i + ".");
}
}
return arrayList;
}
}

View File

@ -13,6 +13,9 @@ import com.facebook.jni.Countable;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader;
import java.util.HashMap;
/**
* Implementation of a read-only map in native memory. This will generally be constructed and filled
* in native code so you shouldn't construct one yourself.
@ -48,6 +51,35 @@ public class ReadableNativeMap extends NativeMap implements ReadableMap {
return new ReadableNativeMapKeySetIterator(this);
}
public HashMap<String, Object>toHashMap() {
ReadableMapKeySetIterator iterator = keySetIterator();
HashMap<String, Object> hashMap = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
switch (getType(key)) {
case Null:
hashMap.put(key, null);
break;
case Boolean:
hashMap.put(key, getBoolean(key));
break;
case Number:
hashMap.put(key, getDouble(key));
break;
case Map:
hashMap.put(key, getMap(key).toHashMap());
break;
case Array:
hashMap.put(key, getArray(key).toArrayList());
break;
default:
throw new IllegalArgumentException("Could not convert object with key: " + key + ".");
}
}
return hashMap;
}
/**
* Implementation of a {@link ReadableNativeMap} iterator in native memory.
*/