问题
I'm having a bad time trying to solve this problem with JAX-RS and I believe that it has something to do with the marshalling/unmarshalling process (that I don't know very much about, I assume), and I want to recreate this:
The REST endpoint to make a post is /rest/register so my services are defined like this:
@ApplicationPath("/rest") public interface RestRegistration { @POST @Path("/register") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) String register(UsernameRegistration usernameAccess, String network) throws RegistrationException; @POST @Path("/register") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) String register(EmailRegistration emailAccess, String network) throws RegistrationException; } public class RestRegistrationImpl implements RestRegistration { public String register(UsernameRegistration usernameAccess, String network) throws RegistrationException { return "StackOverflow example: username=" + usernameAccess.getUser + ", network="+network; } public String register(EmailRegistration emailAccess, String network) throws RegistrationException{ return "StackOverflow example: email=" + emailAccess.getEmail + ", network="+network; } }
It should receive at least two different JSON messages:
{ "usernameAccess" : { "user" : "AUser", "password" : "APass"}, "network" : "Facebook"}
or...
{ "emailAccess" : { "email" : "AnEmail@domain.com", "password" : "APass"}, "network" : "LinkedIn"}
The classes are represented by
public abstract class Registration { private Long _id; private String _password; private String _network; // usual getters and setters... } public class UsernameRegistration extends Registration { private String _user; // usual getters and setters... } public class EmailRegistration extends Registration { private String _email; // usual getters and setters... }
So, my problem now is:
- With this implemenationt I keep receiving an HTTP 500 error.
- And I'm not sure on how to separate the two JSON nodes: usernameAccess/emailAccess and network.
- Also: is there any way on how can I improve using the fact that both classes "UsernameRegistration" and "EmailRegistration" inherit from the same "Registration", making the classes on the "upper" 1. look more elegant?
Is there any bibliography, article or howto someone can hand me over? Thanks in advance! :)
回答1:
In Jackson, your inheritance structure needs to include @JsonTypeInfo
and @JsonSubTypes
with a @JsonSubTypes.Type
for each implementation that you're registering. JsonTypeInfo will require a unique identifier to differentiate the types.
来源:https://stackoverflow.com/questions/27192287/jax-rs-polymorphic-post-request-how-should-i-write-my-json