Solved : A message body reader for Java class and MIME media type application/xml was not found

If you are writing a REST client with Jersey and expecting a XML response which will be converted to Java object you may get MIME media type application/xml was not found exception.

For example see the following client code

package  com.freetipscentral;

import javax.ws.rs.core.MediaType;

import com.freetipscentral.domain.Book;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

public class JerseyRestGetClient {
  public static void main(String args[]) {
    
    Client client = Client.create();
    WebResource resource = client.resource("http://localhost:8080/RestWebService/rest/getXML");
    
    Book response =resource.accept(MediaType.APPLICATION_XML)
    .get(Book.class);
    
    System.out.println(response);
  }
}

This code can generate the following error –

Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class com.freetipscentral.domain.Book, and Java type class com.freetipscentral.domain.Book, and MIME media type application/xml was not found
  at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:549)
  at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:506)xx

The main reason is The Book.java class has no XMLRootElement Mapping as follows.

package com.freetipscentral.domain;

public class Book {
  
  String name;
  int serialNumber;
  
  public Book() {}
  
  public Book(String name, int serialNumber) {
    this.name = name;
    this.serialNumber = serialNumber;
  }
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSerialNumber() {
    return serialNumber;
  }

  public void setSerialNumber(int serialNumber) {
    this.serialNumber = serialNumber;
  }

  public String toString() {
    return serialNumber + " "  + name;
  }	
}

Due to the above condition the xml coming back from the REST service is not converted to Java object.  The solution is to add the XmlRootElelement annotation as follows.

package com.freetipscentral.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Book {
  
  String name;
  int serialNumber;
  
  public Book() {}
  
  public Book(String name, int serialNumber) {
    this.name = name;
    this.serialNumber = serialNumber;
  }
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSerialNumber() {
    return serialNumber;
  }

  public void setSerialNumber(int serialNumber) {
    this.serialNumber = serialNumber;
  }

  public String toString() {
    return serialNumber + " "  + name;
  }	
}

Doing this will resolve the problem of  MIME media type application/xml was not found.