-
Notifications
You must be signed in to change notification settings - Fork 546
Closed
Labels
Milestone
Description
问题描述
简要描述您碰到的问题。
JSON将map转成Java对象出现类型转换未达预期的问题
环境信息
请填写以下信息:
- OS信息: win11
- JDK信息: OpenJdk17.0.1
- 版本信息:Fastjson2 2.0.53
重现步骤
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"希望小学\",\"students\":{\"age\":\"12\",\"id\":\"1\",\"name\":\"张宇\"}}";
School schoolOne = JSON.parseObject(json, School.class);
JSONObject schoolTwo = JSON.parseObject(json);
School schoolThree = schoolTwo.toJavaObject(School.class);
JSONObject studentOne = schoolTwo.getJSONObject("students");
JSONArray studentTwo = schoolTwo.getJSONArray("students");
System.out.println(studentTwo.toString());
}
@Data
private static class School{
private String name;
private List<Student> students;
}
@Data
private static class Student{
private String name;
private String id;
private String age;
}
}期待的正确结果
对于fastjson能够将对象根据目标类型自动转换成array我是认可的,希望能够保留这个特性,对于那些不期望这个特性的可以加一个参数允许关闭这个特性。
说回正题,如图所示schoolOne ,schoolTwo ,studentOne 和studentTwo 是符合预期的转换,但是schoolThree 却未达到预期,经过转换后内部的students数据丢失了,数组大小为0,期望的结果是能够根据目标类型,将map转成对象数组。
如果这个功能一开始就不支持也就罢了,经过测试,json字符串直接解析是可以正常转换,而通过map进行转换缺不能达到预期,希望二者能够保持一致
