blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

JAX-RS: Sending XML data

Instead of transforming XML to and from native Java types in a tedious manner, you can leverage the advantages of using JAXB objects. Even though you can use the javax.xml.transform.Source,, or java.lang.String interfaces or even a simple byte array to store the XML either as a request or response entity, JAXB enables easier data binding

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public class Note {

    private Long id;
    private String text;

    public Note() {

    public Note(Long id, String text) { = id;
        this.text = text;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getText() {
        return text;

    public void setText(String text) {
        this.text = text;


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

public class NotesList {

    private List<note> notes = new ArrayList<note>();

    public NotesList() {

    public List getNotes() {
        return notes;

    public void setNotes(List notes) {
        this.notes = notes;

public class HelloResource {

    public NotesList list() {
        List listOfNotes = new ArrayList();
        listOfNotes.add(new Note(1L,"one"));
        listOfNotes.add(new Note(2L,"two"));
        NotesList response = new NotesList();
        return response;

You could write a client or test it using a tool like Advanced Rest client chrome extension.

By default, the JAX-RS runtime environment attempts to create and use a default JAXBContext class for JAXB classes. However, if the default JAXBContext class is not suitable, then you can supply a JAXBContext class for the application using a JAX-RS ContextResolver provider interface.

This scenario might occur because of complexities of the JAXB classes for the application. You must add the @Provider annotation to the class; for example:

//below example from IBM knowledge center
public class MyContextResolver implements ContextResolver<jaxbcontext> {
     public JAXBContext getContext(Class<?> aType) {
         if(aType == Book.class) {
             JAXBContext myContext = /* This statement creates create a JAXB Context. */ 
             return myContext;
         /* This method returns null for any types not understood.
            If null is returned, other application supplied ContextResolver<jaxbcontext>
            will be used if available */
         return null;
Add this class to the set of classes to return in your application sub-class, just as you did with your resource classes.

No comments:

Post a Comment