Skip to content

Commit

Permalink
fixed nested java objects in json.stringify
Browse files Browse the repository at this point in the history
  • Loading branch information
tonygermano committed Apr 16, 2021
1 parent c86875e commit b989f89
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/org/mozilla/javascript/NativeJSON.java
Original file line number Diff line number Diff line change
Expand Up @@ -298,10 +298,10 @@ private static Object str(Object key, Scriptable holder,
value = ((NativeJavaObject) value).unwrap();
if (value instanceof Map) {
Map<?,?> map = (Map<?,?>) value;
NativeObject nObj = new NativeObject();
Scriptable nObj = state.cx.newObject(state.scope);
map.forEach((k, v) -> {
if (k instanceof CharSequence) {
nObj.put(((CharSequence) k).toString(), nObj, v);
nObj.put(((CharSequence) k).toString(), nObj, state.cx.getWrapFactory().wrap(state.cx, state.scope, v, v.getClass()));
}
});
value = nObj;
Expand All @@ -312,7 +312,11 @@ private static Object str(Object key, Scriptable holder,
value = col.toArray(new Object[col.size()]);
}
if (value instanceof Object[]) {
value = new NativeArray((Object[]) value);
Object[] elements = (Object[]) value;
elements = Arrays.stream(elements)
.map(o -> state.cx.getWrapFactory().wrap(state.cx, state.scope, o, o.getClass()))
.toArray();
value = state.cx.newArray(state.scope, elements);
}
}
}
Expand Down
23 changes: 23 additions & 0 deletions testsrc/jstests/stringify-java-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,27 @@ assertTrue(expected.test(actual));
var obj = {test: javaObject};
assertThrows(()=>JSON.stringify(obj), TypeError);

// nested Maps and Lists
var map1 = new java.util.HashMap({a:1});
var map2 = new java.util.HashMap({b:2, map1: map1});

var list1 = new java.util.ArrayList([1]);
var list2 = new java.util.ArrayList([2, list1]);

var expected = JSON.stringify({
b: 2,
map1: {a: 1}
});
var actual = JSON.stringify(map2);
assertEquals(expected, actual);

var expected = JSON.stringify([2, [1]]);
var actual = JSON.stringify(list2);
assertEquals(expected, actual);

list2.add(map1);
var expected = JSON.stringify([2, [1], {a:1}]);
var actual = JSON.stringify(list2);
assertEquals(expected, actual);

"success"

0 comments on commit b989f89

Please sign in to comment.