Skip to content

Commit

Permalink
fix deserialize HashMap subclass, for issue alibaba#1686
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jul 26, 2023
1 parent 3163899 commit 62bb3d9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,20 @@ public static ObjectReader of(Type fieldType, Class mapType, long features) {
return new ObjectReaderImplMap(instanceType, features, Collections.EMPTY_MAP);
}
default:
Type genericSuperclass = instanceType.getGenericSuperclass();
if (mapType != JSONObject.class && genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type[] arguments = parameterizedType.getActualTypeArguments();
if (arguments.length == 2) {
Type arg0 = arguments[0];
Type arg1 = arguments[1];
boolean typed = !(arg0 instanceof TypeVariable || arg1 instanceof TypeVariable);
if (typed) {
return new ObjectReaderImplMapTyped(mapType, instanceType, arg0, arg1, 0, builder);
}
}
}

if (instanceType == JSONObject1O.class) {
builder = createObjectSupplier(CLASS_JSON_OBJECT_1x);
instanceType = LinkedHashMap.class;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.alibaba.fastjson2.issues_1600;

import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Test;

import java.util.HashMap;

public class Issue1686 {
@Test
public void test_nest_map_subclass() {
A a = new A();
a.put("a", new B());
a.get("a").put("b", "1");

String jsonString = JSON.toJSONString(a);
assert jsonString.equals("{\"a\":{\"b\":\"1\"}}");

A a1 = JSON.parseObject(jsonString, A.class);
// java.lang.ClassCastException: com.alibaba.fastjson2.JSONObject cannot be cast to B
assert a1.get("a").get("b").equals("1");
}

public static class A
extends HashMap<String, B> {
}

public static class B
extends HashMap<String, String> {
}
}

0 comments on commit 62bb3d9

Please sign in to comment.