krasserm / grails-jaxrs

JAX-RS Plugin for Grails
http://code.google.com/p/grails-jaxrs/
Apache License 2.0
50 stars 48 forks source link

MessageBodyReaderSupport for DTO Classes? #38

Closed confile closed 10 years ago

confile commented 10 years ago

I want to use the Grails-jaxrs plugin to implement a custom MessageBodyReaderSupport to read a UserDto class from a client.

How do I have to implement the UserDtoReader in order to get an instance of the UserDto?

This is my UserDto class:

public class UserDto {
    private String firstName;
    private String lastName;

    public UserDto() {
        firstName = "";
        lastName = "";
    }

    public UserDto(String firstName,
                   String lastName) {

        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        String s = " { User ";
        s += "id=" + id + " ";
        s += "firstName=" + firstName + " ";
        s += "lastName=" + lastName + " ";
        s += " User } ";
        return s;
    }
}

This is my UserDtoReader class:

@Consumes("application/json")
class UserDtoReader extends MessageBodyReaderSupport<UserDto> {

    @Override
    public UserDto readFrom(MultivaluedMap<String, String> httpHeaders,
            InputStream entityStream) throws IOException,
            WebApplicationException {
        // TODO Auto-generated method stub
        return null;
    }
}
davidecavestro commented 10 years ago

Did you try with something like the following?

@Provider
@Consumes("application/json")
class UserDtoReader extends MessageBodyReaderSupport<UserDto> {

    @Override
    public UserDto readFrom(MultivaluedMap<String, String> httpHeaders,
            InputStream entityStream) throws IOException,
            WebApplicationException {
        return new JsonSlurper().parse(new InputStreamReader(entityStream))
    }
}

PS: Please also note you missed the @javax.ws.rs.ext.Provider annotation on the reader. It is needed as per https://github.com/krasserm/grails-jaxrs/wiki/Advanced-Features#custom-providers

confile commented 10 years ago

@davidecavestro Great it works perfect thank you. I think it would be helpful, if you add the method as an example to your documentation.

davidecavestro commented 10 years ago

Just added it to the wiki at http://github.com/krasserm/grails-jaxrs/wiki/Advanced-Features#further-entity-provider-support Cheers Davide

confile commented 10 years ago

great thank you