简体   繁体   中英

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

List<UserDTO> getUsers();

getUsers returns a list of users and if I print the object(The variable obj here) I can see them.

The obj is actually a json response as below

[{firstName=A,lastName=B,emailAddress=AB@email.com},{firstName=C,lastName=D,emailAddress=CD@email.com},{firstName=E,lastName=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. 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.

Any idea how to fix this or what's going wrong here?

getUsers/setUsers from another DTO

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;
}

UserDTO

    private String s$firstName;
private String s$lastName;
private String s$emailAddress;

and their getter/setters

All the DTOs are getting set from json parsing.

Are you saying that not all items in the list are 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM