@xmlrootelement json等价物

时间:2014-04-07 20:05:53

标签: java json jersey

这是我用来填充和发送它作为我的Web服务请求调用的一部分的类:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ClientInfo {

    private String langCode;
    private String userId;
    private String password;
    private String ShipTo;
    private String timeZone;
    public String getLangCode() {
        return langCode;
    }
    public void setLangCode(String langCode) {
        this.langCode = langCode;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getShipTo() {
        return ShipTo;
    }
    public void setShipTo(String shipTo) {
        ShipTo = shipTo;
    }
    public String getTimeZone() {
        return timeZone;
    }
    public void setTimeZone(String timeZone) {
        this.timeZone = timeZone;
    }

}

当我使用Entity.xml()来解析类并启动请求时,一切正常,我得到结果,这是服务调用代码的一部分。请查看Entity.xml();

的最后一行
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;

ClientInfo ci = new ClientInfo();
ci.setLangCode("en");
ci.setPassword("password@123");
ci.setShipTo("0000");
ci.setTimeZone("420");
ci.setUserId("user1");
Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.post(Entity.xml(ci));

但是,如果我将Entity.xml(ci)更改为Entity.json(ci),则会引发异常。例外情况如下:

Apr 07, 2014 3:54:08 PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.sheidaei.sample.appleclient.ClientInfo, genericType=class com.sheidaei.sample.appleclient.ClientInfo.

根据我的阅读,我的理解是应用程序找不到ClientInfo类的JSON表示。是否有一种简单的方法(如注释),以便Entity.json()轻松找到ClientInfo的JSON表示?

1 个答案:

答案 0 :(得分:1)

默认情况下,Jersey为JAXB带注释的类和XML编组/解组提供支持。要使用JSON,您需要具有适当配置的适当实体提供程序。

Jersey文档提供了详细信息:https://jersey.java.net/documentation/1.18/json.html