users@jersey.java.net

Re: [Jersey] Simple attempt to output JSON from JAXB class still returning JAXB

From: Jakub Podlesak <Jakub.Podlesak_at_Sun.COM>
Date: Wed, 04 Nov 2009 18:17:00 +0100

Hi,

please see inline...

On Wed, Nov 04, 2009 at 05:05:00PM +0000, Paul Taylor wrote:
> I have happily been generating XML from some JAXB classes created from
> an Xmlschema for some time, I now also need to allow output as JSON
>
>
> I'm using Maven and and added
>
> <dependency>
> <groupId>com.sun.jersey</groupId>
> <artifactId>jersey-json</artifactId>
> <version>1.1.2-ea</version>
> </dependency>
>
> I already had
>
> <dependency>
> <groupId>com.sun.xml.bind</groupId>
> <artifactId>jaxb-impl</artifactId>
> <version>2.1.12</version>
> <scope>test</scope>
> </dependency>
>
> this was my existing XML top level method (Metadata is the root JAXB class)
>
> public void write(PrintWriter out, Results results,) throws IOException {
> try {
> Metadata metadata = write(results);
> Marshaller m = context.createMarshaller();
> m.marshal(metadata, out);
> }
> catch (JAXBException je) {
> throw new IOException(je);
> }
>
> }
>
> and I added these new Json Methods:
>
> static final JAXBContext jsoncontext = initJsonContext();
>
> public String getJsonMimeType() {
> return "application/json; charset=UTF-8";
> }
>
> private static JAXBContext initJsonContext() {
> try {
> return JSONJAXBContext.newInstance("org.musicbrainz.mmd2");
> }
> catch (JAXBException ex) {
> //Unable to initilize jaxb context, should never happen
> throw new RuntimeException(ex);
> }
> }
>
> public void writeJson(PrintWriter out, Results results) throws
> IOException {
> try {
> Metadata metadata = write(results);
> Marshaller m = jsoncontext.createMarshaller();

instead of creating Marshaller, try to get JSONMarshaller (see [1])
and than call marshallToJSON method ([2]).

HTH,

~Jakub

[1]https://jersey.dev.java.net/nonav/apidocs/1.1.2-ea/jersey/com/sun/jersey/api/json/JSONJAXBContext.html#createJSONMarshaller()
[2]https://jersey.dev.java.net/nonav/apidocs/1.1.2-ea/jersey/com/sun/jersey/api/json/JSONMarshaller.html#marshallToJSON%28java.lang.Object,%20java.io.Writer%29

> m.marshal(metadata, out);
> }
> catch (JAXBException je) {
> throw new IOException(je);
> }
>
> but its still returning xml, Ive double checked that I deployed
> properly, so is there anything else I have to do or should this work.
>
> thanks Paul
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>

-- 
Jakub Podlešák
Software Engineer at SUN Microsystems And CZJUG Co-Leader
http://blogs.sun.com/japod