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();
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