Skip to content

Instantly share code, notes, and snippets.

@sherman
Created September 28, 2012 10:18
Show Gist options
  • Save sherman/3799022 to your computer and use it in GitHub Desktop.
Save sherman/3799022 to your computer and use it in GitHub Desktop.
new JsonDeserializer<NativeObject>() {
@Override
public NativeObject deserialize(
JsonElement json,
Type type,
JsonDeserializationContext context
) {
NativeObject object = RhinoUtils.createJsObject(globalCtx);
JsonObject jsonObject = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
JsonElement elt = entry.getValue();
String propertyName = entry.getKey();
if (elt.isJsonPrimitive()) {
JsonPrimitive value = elt.getAsJsonPrimitive();
if (value.isBoolean()) {
addProperty(object, propertyName, value.getAsBoolean());
} else if (value.isNumber()) {
addProperty(object, propertyName, context.deserialize(elt, Number.class));
} else {
addProperty(object, propertyName, value.getAsString());
}
} else if (elt.isJsonObject()) {
addProperty(object, propertyName, context.deserialize(elt, NativeObject.class));
} else if (elt.isJsonArray()) {
addProperty(object, entry.getKey(), transformArray(elt, context));
} else {
throw new JsonSyntaxException("Trying to deserialize unknown type:" + entry.getValue());
}
}
return object;
}
private NativeArray transformArray(JsonElement elt, JsonDeserializationContext context) {
JsonArray jsonArray = elt.getAsJsonArray();
NativeArray array = new NativeArray(jsonArray.size());
int i = 0;
for (JsonElement jsonArrayElt : jsonArray) {
if (jsonArrayElt.isJsonPrimitive()) {
JsonPrimitive value = jsonArrayElt.getAsJsonPrimitive();
if (value.isBoolean()) {
array.put(i++, array, value.getAsBoolean());
} else if (value.isNumber()) {
array.put(i++, array, context.deserialize(value, Number.class));
} else {
array.put(i++, array, value.getAsString());
}
} else if (jsonArrayElt.isJsonObject() || jsonArrayElt.isJsonArray()) {
array.put(i++, array, context.deserialize(jsonArrayElt, NativeObject.class));
} else {
throw new JsonSyntaxException("Trying to deserialize unknown type:" + elt);
}
}
return array;
}
private void addProperty(NativeObject object, String name, Object value) {
object.defineProperty(name, value, ScriptableObject.EMPTY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment