users@jersey.java.net

[Jersey] Re: How to return List<String> by GET?

From: Christopher Piggott <cpiggott_at_gmail.com>
Date: Mon, 14 Mar 2011 08:41:33 -0400

On Mon, Mar 14, 2011 at 5:58 AM, Pengfei Di <pengfei.di_at_match2blue.com> wrote:
> Is it possible to return List<String> at all? If yes, how can I write the
> message body writer for it?

When you return List<SomeObject> with an XML or JSON representation
it's pretty apparent how jersey can take that single object and put it
into a list. It builds a wrapper around it, by pluralizing
SomeObject, something like:

<SomeObjects>
    <SomeObject> ... </SomeObject>
    <SomeObject> ... </SomeObject>
</SomeObjects>

You can still pick out the individual objects - they have a beginning
and an end.

If you sent back a list of Strings, in some representation that you
create yourself, said representation would have to have some way to
determine where each individual string starts and stops. In the
totally generic case you couldn't use \n because strings can have \n
in them. I don't think it would be entirely unreasonable for you to
create a message body writer that takes each individual string and
encodes it to convert (at least) newlines to some other character
sequence, then a MessageBodyReader at the other end to convert it
back.

But my gut feeling is that you'd be better off making a jaxb object
ListOfStrings with an element List<String> in it, and let jaxb (or
similar) worry about how to encode (with escapes) said string. But,
doing it yourself is not a totally crazy idea, especially if you don't
already have jaxb etc. in your application.

--Chris