有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

CXFJaxRS WebClient的java自定义对象输入

我是RESTful的新手,尝试创建一个示例服务来实现POST on void方法。我能够测试String类的方法,但在使用自定义对象进行测试时出现异常

服务类:

@Override
@POST
@Path("/sayHello")
public void sayHello(Person person) {
    System.out.println("Hello there, " + person.getName());         
}

@Override
@POST
@Path("/sayHi")
public void sayHi(String name) {
    System.out.println("Hey there, " + name);       
}   

测试客户端:

public void testSayHelloRest() throws Exception { 
    WebClient client = WebClient.create("http://localhost:8080/ServicesTutorial/sampleService/sayHello");
    Person p = new Person();
    p.setName("My Name");           
    client.post(p);
   }

public void testSayHi() throws Exception {    
    WebClient client = WebClient.create("http://localhost:8080/ServicesTutorial/sampleService/sayHi");  
    client.post("My Name"); 
}

使用简单字符串输入的第二个测试通过,但第一个测试失败,出现以下异常

org.apache.cxf.interceptor.Fault: .No message body writer has been found for class : class com.wk.services.data.Person, ContentType : application/xml.

个人类别

public class Person {
    private String name;

    public String getName() {
        return name;
    }

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

共 (1) 个答案

  1. # 1 楼答案

    您需要如下注释Person类:

    @XmlRootElement(name="Person")
    @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
    public class Person {
        private String name;
    
        @XmlElement (name = "name")
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }       
    }