Skip to content

Instantly share code, notes, and snippets.

@eleco
Created July 25, 2014 15:28
Show Gist options
  • Save eleco/c2bc77dca9ecc844a924 to your computer and use it in GitHub Desktop.
Save eleco/c2bc77dca9ecc844a924 to your computer and use it in GitHub Desktop.
transform json native object to java map
import sun.org.mozilla.javascript.internal.Context;
import sun.org.mozilla.javascript.internal.NativeArray;
import sun.org.mozilla.javascript.internal.NativeObject;
import sun.org.mozilla.javascript.internal.Scriptable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static Map mapFromScriptable(Scriptable obj){
final Map<String, Object> map = new HashMap();
for (Object propId : NativeObject.getPropertyIds(obj)){
String key = propId.toString();
Object value = NativeObject.getProperty(obj, key);
map.put(key, parseValue(value));
}
return map;
}
private static Object parseValue(Object value){
if (value instanceof NativeObject){
return mapFromScriptable((NativeObject)value);
}
else if (value instanceof NativeArray){
NativeArray array = (NativeArray)value;
List<Map> listOfMaps = new ArrayList();
for (Object element:array.getIds()){
int index = (Integer) element;
listOfMaps.add(mapFromScriptable((Scriptable) array.get(index, null)));
}
return listOfMaps;
}
else {
String strValue = value.toString();
if(strValue.endsWith(".0")) strValue = strValue.substring(0, strValue.length()-2);
return strValue;
}
}
public static void main(String args[]){
Context ctx = Context.enter();
try {
Scriptable scope = ctx.initStandardObjects();
NativeObject result = (NativeObject) ctx.evaluateString(scope, "({\"test\":[{\"a\":1},{\"b\":2}]})","test",1,null) ;
System.out.println(mapFromScriptable((Scriptable)result));
} finally{
Context.exit();
}
}
}
@eleco
Copy link
Author

eleco commented Jul 25, 2014

sun.org.mozilla.javascript.internal.* classes linked from Java 6 rt.jar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment