[英]Cast Object to List of Custom DTOs in java
Here's the code: 这是代码:
Object obj = getUsers();
List<UserDTO> userDTOList = new ArrayList<UserDTO>();
userDTOList = (ArrayList<UserDTO>)obj;
for (UserDTO userDTO : userDTOList) {
do some stuff with userDTO
}
The signature of "getUsers()" is as below “ getUsers()”的签名如下
List<UserDTO> getUsers();
getUsers returns a list of users and if I print the object(The variable obj here) I can see them. getUsers返回用户列表,如果我打印对象(此处为obj变量),则可以看到它们。
The obj is actually a json response as below obj实际上是一个json响应,如下所示
[{firstName=A,lastName=B,emailAddress=AB@email.com},{firstName=C,lastName=D,emailAddress=CD@email.com},{firstName=E,lastName=F,emailAddress=EF@email.com}]
[{的firstName = A,姓氏= B,EMAILADDRESS = AB @ email.com},{的firstName = C,姓氏= d,EMAILADDRESS = CD @ email.com},{的firstName = E,姓氏= F,EMAILADDRESS = EF @ email.com}]
Now the problem I'm facing is: 现在我面临的问题是:
After the casting when I'm iterating over the casted userDTOList I see all the individual userDTOs carry the same data though actually they are different as I can confirm when I print the object. 投射后,当我遍历投射的userDTOList时,我看到所有单个的userDTO都携带相同的数据,尽管实际上它们是不同的,正如我在打印对象时可以确认的那样。 It's like the first user information is getting copied to others.
就像第一个用户信息被复制到其他人一样。
As with the example above, the 3 userDTOs should carry individual user information, but I'm getting say firstName=A for the three DTOs. 与上面的示例一样,3个userDTO应该携带单独的用户信息,但是我要说的是三个DTO的firstName = A。
Any idea how to fix this or what's going wrong here? 知道如何解决此问题或这里出了什么问题吗?
private List<UserDTO> s$user;
public List<UserDTO> getUsers() {
return s$user;
}
public void sets$user(List<UserDTO> s$user) {
this.s$user = s$user;
}
private String s$firstName;
private String s$lastName;
private String s$emailAddress;
and their getter/setters 和他们的getter / setter
All the DTOs are getting set from json parsing. 所有DTO都通过json解析进行设置。
Are you saying that not all items in the list are UserDtos? 您是不是在说列表中的所有项目都不是UserDtos? If so try:
如果是这样,请尝试:
Object obj = getUsers();
List<Object> userDtoList = (ArrayList<Object>) obj;
for (Object userDtoObject : userDtoList) {
if (userDtoObject instanceof UserDto) {
UserDto userDto = (UserDto) userDtoObject;
// Do stuff with userDto...
}
}
Edit: 编辑:
If you are getting a JSON response, you should not cast it, you should be using a library such as: 如果收到JSON响应,则不应该强制转换它,而应使用诸如以下的库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.