Created
July 25, 2014 15:28
-
-
Save eleco/c2bc77dca9ecc844a924 to your computer and use it in GitHub Desktop.
transform json native object to java map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sun.org.mozilla.javascript.internal.* classes linked from Java 6 rt.jar