所以我在这个问题上已经坐了一段时间了。我想把这个JSON字符串转换成一个项目对象。(Projekt类如下)
String projectEmptyString = "{\"id\":1,\"name\":\"Seminararbeit Geschichte\",\"description\":\"Der Wilde Westen\",\"comments\":[],\"appointments\":[{\"id\":1,\"name\":\"AppointmentSample\",\"description\":\"AppointmentSample\",\"startDate\":{\"day\":1,\"month\":2,\"year\":2020,\"hour\":4,\"minute\":5},\"endDate\":{\"day\":5,\"hour\":2,\"minute\":1,\"month\":4,\"year\":3},\"type\":\"DEADLINE\"}],\"handlers\":[],\"processors\":[],\"type\":\"SEMINARARBEIT\"}";
它不会工作.我已经得出结论,如果我设置约会数组空这样。
\"appointments\":[]
转换工作。所以必须有一个 在反序列化到任命对象时失败.
\"appointments\":[{\"id\":1,\"name\":\"AppointmentSample\",\"description\":\"AppointmentSample\",\"startDate\":{\"day\":1,\"month\":2,\"year\":2020,\"hour\":4,\"minute\":5},\"endDate\":{\"day\":5,\"hour\":2,\"minute\":1,\"month\":4,\"year\":3},\"type\":\"DEADLINE\"}]
我真的很想知道GSON这里的问题是什么?
项目类::
public class Project {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
@SerializedName("comments")
private ArrayList<Comment> comments;
@SerializedName("appointments")
private Collection<Appointment> appointments;
@SerializedName("handlers")
private Collection<User> handlers;
@SerializedName("processors")
private Collection<User> processors;
@SerializedName("type")
private ProjectType projectType;
// constructor, getter, setter,...
}
任命类:
public class Appointment {
private int id;
private String name;
private String description;
private Date startDate;
private Date endDate;
@SerializedName("type")
private AppointmentType appointmentType;
// constructor, getter, setter,...
}
奇怪的是,如果我在注释数组中填入数据,并将appointment数组设置为空--使用相同的json结构(我想)--就能正常工作,见下面。
"[{\"id\":1,\"content\":\"Der Wilde Westen war im 19. Jahrhundert!\",\"restricted\":true,\"wasEdited\":false,\"creationTime\":{\"day\":1,\"month\":5,\"year\":2020,\"hour\":12,\"minute\":30},\"author\":{\"id\":1,\"username\":\"LuckyLuke\",\"email\":\"[email protected]\",\"roles\":[\"ROLE_ADMIN\"],\"userInfo\":{\"id\":1,\"forename\":\"Lucky\",\"surname\":\"Luke\",\"studentNumber\":1234567}}},{\"id\":2,\"content\":\"Cowboys sind ja so doof!\",\"restricted\":false,\"wasEdited\":true,\"creationTime\":{\"day\":3,\"month\":5,\"year\":2020,\"hour\":15,\"minute\":49},\"author\":{\"id\":3,\"username\":\"JackDalton\",\"email\":\"[email protected]\",\"roles\":[\"ROLE_USER\"],\"userInfo\":{\"id\":3,\"forename\":\"Jack\",\"surname\":\"Dalton\",\"studentNumber\":7654312}}}]"
我知道,这可能是太多的输入,但我真的在绝望的边缘... ...
EDIT1:
projectString显示在上面
Project projekt = newGson().fromJson(projectString, Project.class);
好吧,我自己解决了。
很明显,GSON不喜欢Inheritage.我把一个用户的id(User.class)传给了它的子类UserInfo(UserInfo.class)。
我去掉了传承,现在一切都好了。