1

I'm new to the Spring Framework and trying to build RESTful web service. Now I'm a bit stuck with this problem.

I have some entity classes like UserDetails (getters/setters, equals() and hashCode() omitted):

public class UserDetails {

    private Long userId;
    private String login;
    private String firstName;
    private String lastName;

    private Map<ActionDetails, Boolean> confirmedActionsMap;
}

and ActionDetails (again getters/setters, equals() and hashCode() omitted):

public class ActionDetails {

    private Long actionId;
    private String actionName;
    private String actionDescription;
}

I have a method in my @RestController returning UserDetails:

@GET
@RequestMapping("/user")
@Produces ({ "application/json" })
public ResponseEntity<User> getUser(){

    UserDetails userDetails = //obtaining user somehow

    return new ResponseEntity<User>(userDetails, HttpStatus.OK);
}

But in response I get JSON with ActionDetails in map not serialized to JSON, but simply called toString() on it:

{
    "userId": 1,
    "login": "j.doe",
    "firstname": "John",
    "lastname": "Doe",
    "confirmedActionsMap": {"com.example.ActionDetails@d4955b30": true}
}

ActionDetails themselves beeing returned by other controller methods are serialized to JSON just fine. What is the most appropriate approach to serialize objects in collections in REST with Spring?

James
  • 1,095
  • 7
  • 20
Tom Sawer
  • 152
  • 1
  • 13

1 Answers1

1

A Map is a representation of key, value pairs. Calling toString() on the key is the only logical way of representing the key.

If you want to serialize the ActionDetail differently, I'd suggest wrapping ActionDetail, Boolean in another class and putting that in a List.

For example:

public class UserDetails {
    private Long userId;
    private String login;
    private String firstName;
    private String lastName;
    private List<ActionDetailWrapper> confirmedActions;
}

public class ActionDetails {
    private Long actionId;
    private String actionName;
    private String actionDescription;
}

public class ActionDetailWrapper {
    private ActionDetails actionDetails;
    private Boolean result;
}

Alternatively you could key your Map using the actionId from ActionDetails and add the Boolean into the ActionDetails class.

James
  • 1,095
  • 7
  • 20