Skip to content

Commit

Permalink
fix: 在使用 JSONObject.toJavaObject 反序列化 JSONObject 到带默认值的 Kotlin 类时遇到问题。#…
Browse files Browse the repository at this point in the history
  • Loading branch information
IceCream-QAQ authored and wenshao committed Nov 28, 2024
1 parent e6ff30a commit d65ca79
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.alibaba.fastjson2.reader;

import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.*;
import com.alibaba.fastjson2.util.Fnv;
import com.alibaba.fastjson2.util.TypeUtils;

Expand Down Expand Up @@ -471,9 +468,16 @@ typeName, getObjectClass(), features | getFeatures()
Class<?> valueClass = fieldValue.getClass();
Class fieldClass = fieldReader.fieldClass;
if (valueClass != fieldClass) {
Function typeConvert = provider.getTypeConvert(valueClass, fieldClass);
if (typeConvert != null) {
fieldValue = typeConvert.apply(fieldValue);
if (fieldValue instanceof JSONObject) {
ObjectReader fieldObjectReader = provider.getObjectReader(fieldReader.fieldType);
fieldValue = fieldObjectReader.createInstance((Map) fieldValue, features);
} else if (fieldValue instanceof JSONArray) {
fieldValue = ((JSONArray) fieldValue).to(fieldReader.fieldType, features);
} else {
Function typeConvert = provider.getTypeConvert(valueClass, fieldClass);
if (typeConvert != null) {
fieldValue = typeConvert.apply(fieldValue);
}
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues_3100/Issue3152.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.alibaba.fastjson2.issues_3100

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


class Issue3152 {

data class Foo(val int: Int = 1, val bar: Bar)
data class Bar(val text: String)

@Test
fun test() {
Assertions.assertEquals(
Foo(1, Bar("hello")),
JSON.parseObject(
"""
{
"bar": {
"text" : "hello"
}
}
""".trimIndent()
).toJavaObject(Foo::class.java)
)
}
}

0 comments on commit d65ca79

Please sign in to comment.