简体   繁体   中英

@XmlRootElement not working in jersey rest

ERROR:

MessageBodyWriter not found for media type=application/xml, type=class com.example.DemoRest2.Employee, genericType=class com.example.DemoRest2.Employee.

I want to return the object of Employee.class in xml format but getting above error. I am using @XmlRootElement annotation. However, it works fine when I return it in string format.

EmployeeRsource.java

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("employee")
public class EmployeeResource {

@GET
@Produces(MediaType.APPLICATION_XML)
public Employee getEmp() {
    
    Employee e1 = new Employee();
    e1.setName("Tom");
    e1.setAge(25);
    System.out.println(e1);
    
    return e1;
}
}

Employee.java

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

private String name;
private int age;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
@Override
public String toString() {
    return "Employee [name=" + name + ", age=" + age + "]";
}   

}

Getting "INTERNAL SERVER ERROR 500" on user interface

I am already having following dependencies: jersey-media-jaxb - 3.0.2 jaxb-api - 2.3.1 jersey-container-servlet-core jersey-hk2 jersey version - 3.0.2

The Jakarta EE Working Group has announced that javax is now officially and finally renamed as jakarta with the release of the Jakarta EE 9 Platform and Web Profile specifications and related TCKs.

To use that @XmlRootElement, import jakarta.xml.bind.annotation.XmlRootElement, after adding following,

<dependency>
        <groupId>jakarta.xml.bind</groupId>
        <artifactId>jakarta.xml.bind-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-jaxb</artifactId>
        <version>2.33</version>
    </dependency>

    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-osgi</artifactId>
        <version>3.0.2</version>
    </dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM