Skip to content

Commit

Permalink
bug fix for toJavaObject, fix issue #728
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Sep 1, 2022
1 parent ae5f807 commit 1621f2a
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
1 change: 0 additions & 1 deletion core/src/main/java/com/alibaba/fastjson2/JSON.java
Original file line number Diff line number Diff line change
Expand Up @@ -2583,7 +2583,6 @@ static <T> T to(Class<T> clazz, Object object) {
* @param clazz converted goal class
* @deprecated since 2.0.4, please use {@link #to(Class, Object)}
*/
@Deprecated
static <T> T toJavaObject(Object object, Class<T> clazz) {
return to(clazz, object);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ public Object createInstance(Map map, long features) {
return map;
}

if (mapType == JSONObject.class) {
return new JSONObject(map);
}

return map;
}

Expand Down
5 changes: 5 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,11 @@ public static <T> T cast(Object obj, Class<T> targetClass) {
}
}

if (obj instanceof Collection) {
ObjectReader objectReader = provider.getObjectReader(targetClass);
return (T) objectReader.createInstance((Collection) obj);
}

throw new JSONException("can not cast to " + targetClass.getName() + ", from " + obj.getClass());
}

Expand Down
46 changes: 46 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue728.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.alibaba.fastjson2.issues;

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

import java.util.ArrayList;
import java.util.LinkedHashMap;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class Issue728 {
@Test
public void test() {
String a = "{\"test\":\"123465\"}";
LinkedHashMap linkedHashMap = JSON.toJavaObject(a, LinkedHashMap.class);
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", linkedHashMap);
Bean bean = jsonObject.toJavaObject(Bean.class);
assertNotNull(bean.data);
Object test = bean.data.get("test");
assertEquals("123465", test);
}

public static class Bean {
public JSONObject data;
}

@Test
public void test1() {
JSONObject jsonObject = new JSONObject();
ArrayList list = new ArrayList();
list.add("123465");
jsonObject.put("data", list);
Bean1 bean = jsonObject.to(Bean1.class);
ArrayList list1 = bean.data;
assertEquals(1, list1.size());
assertEquals(list.get(0), list1.get(0));
}

public static class Bean1 {
public JSONArray data;
}
}

0 comments on commit 1621f2a

Please sign in to comment.