users@jersey.java.net

Re: [Jersey] Unmarshaling JAXB object from JSON

From: Farrukh Najmi <farrukh_at_wellfleetsoftware.com>
Date: Thu, 02 Apr 2009 20:45:16 -0400

 
>>> On Apr 1, 2009, at 4:45 PM, Farrukh Najmi wrote:
>>>
>>>
>>>> OK so my code now looks like this:
>>>>
>>>> List<String> postalAddresses = ...
>>>> for (String postalAddressStr : postalAddresses) {
>>>> MessageBodyReader r =
>>>> providers.getMessageBodyReader(PostalAddressType.class,
>>>> PostalAddressType.class, new Annotation[1],
>>>> MediaType.APPLICATION_JSON_TYPE);
>>>> PostalAddressType postalAddress =
>>>> (PostalAddressType) r.readFrom(PostalAddressType.class,
>>>> PostalAddressType.class, new Annotation[1],
>>>> MediaType.APPLICATION_JSON_TYPE,
>>>> new InBoundHeaders(),
>>>> new ByteArrayInputStream(postalAddressStr.getBytes()));
>>>> org.getPostalAddress().add(postalAddress);
>>>> }

Hi Guys,

I am now cleaning up my code and trying to write a utility generic class
that converts from List<String> of JSON String to List<T> where T
represent the type of my JAXB bean. I am close and the class looks like
this:

    public class JSONToJAXBConvertor<T> {

        /**
         * Convert a List of JSON String intoa List of corresponding
JAXB beans.
         *
         * @param formParamsMulti the form parameters
         * @param formParam the name of a specific form parameter whose
value is a List<String> where each String is a JSON String
         * @return the List of JAXB beans that have been unmarshalled
from List of JSON Strings
         * @throws java.io.IOException
         */
        public List<T> convertJSONToJAXB(MultivaluedMap<String, String>
formParamsMulti, String formParam) throws IOException {
            List<T> jaxbObjects = new ArrayList<T>();

            List<String> jsonStrings =
getListValueFromMultiValuedMap(formParamsMulti, formParam);
            for (String jsonString : jsonStrings) {
                MessageBodyReader r =
providers.getMessageBodyReader(PostalAddressType.class,
PostalAddressType.class, new Annotation[1],
MediaType.APPLICATION_JSON_TYPE);
                T jaxbObject = (T) r.readFrom(PostalAddressType.class,
PostalAddressType.class, new Annotation[1], MediaType.APPLICATION_JSON_TYPE,
                    new InBoundHeaders(),
                    new ByteArrayInputStream(jsonString.getBytes()));
                jaxbObjects.add(jaxbObject);
            }

            return jaxbObjects;
        }
    }

Assume T above is PostalAddressType. What I can't figure out is how to
replace PostalAddressType.class using generics code and Type T.
Replacing it with T.class is not legal. Perhaps I need to do something
with jaxbObjects?

So if "List<T> jaxbObjects" is really "List<PostalAddressType>
jaxbObjects" how can I get the class for PostalAddressType?

Thanks for any tips on what is really just a Java generics question.

-- 
Regards,
Farrukh
Web: http://www.wellfleetsoftware.com