Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion core/src/main/java/com/alibaba/fastjson2/JSONObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -1292,7 +1292,12 @@ public <T> T to(Class<T> clazz, JSONReader.Feature... features) {

ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
ObjectReader<T> objectReader = provider.getObjectReader(clazz, fieldBased);
return objectReader.createInstance(this, featuresValue);

try {
return objectReader.createInstance(this, featuresValue);
} catch (UnsupportedOperationException e) {
return JSON.parseObject(this.toJSONString(), clazz, features);
}
}

public void copyTo(Object object, JSONReader.Feature... features) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.alibaba.fastjson2.issues_3900;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.reader.ObjectReader;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Type;

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

public class Issue3901 {
@Test
public void test() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "James");

JSON.register(User.class, new UserReader());
User user = jsonObject.to(User.class);
assertEquals("ZhangSan", user.getName());
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public static class User {
private String name;
}

public static class UserReader implements ObjectReader {
@Override
public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
jsonReader.readObject();
return new User("ZhangSan");
}
}
}
Loading