我有一個使用POJO的REST服務。下面是方法:Java REST服務接受POJO,但字段始終爲空
@POST
@Path("terminate")
@Produces({"application/xml", "application/json"})
@Consumes({"application/xml", "application/json"})
public TerminateActorCommand terminateActor(TerminateActorCommand cmd) {
System.out.println("Running terminate: " + cmd);
Query query = em.createNamedQuery("Actor.terminate");
query.setParameter("eid", cmd.getActorEid());
query.executeUpdate();
return cmd;
}
這裏是POJO
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author mike
*/
@XmlRootElement
public class TerminateActorCommand {
String actorEid;
String terminatorEid;
String reason;
Date effectiveTerminationDate;
public TerminateActorCommand() {
}
@JsonCreator
public TerminateActorCommand(@JsonProperty("actorEid") String actorEid, @JsonProperty("terminatorEid") String terminatorEid,
@JsonProperty("reason") String reason) { //, @JsonProperty("effectiveTerminationDate") Date effectiveTerminationDate) {
this.actorEid = actorEid;
this.terminatorEid = terminatorEid;
this.reason = reason;
//this.effectiveTerminationDate = effectiveTerminationDate;
}
public CommandType getCommandType() {
return CommandType.TERMINATE_ACTOR;
}
public String getActorEid() {
return actorEid;
}
public String getTerminatorEid() {
return terminatorEid;
}
public String getReason() {
return reason;
}
public Date getEffectiveTerminationDate() {
return effectiveTerminationDate;
}
@Override
public String toString() {
return "TerminateActorCommand{" + "actorEid=" + actorEid + ", terminatorEid=" + terminatorEid + ", reason=" + reason + ", effectiveTerminationDate=" + effectiveTerminationDate + '}';
}
}
當我把這個用捲曲:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"actorEid":"mb995a", "terminatorEid":"mb995a","reason":"testing"}' http://127.0.0.1:8080/actor-service/webresources/net.mikeski.auth.entities.actors/terminate
我得到的返回值,看看print語句,但TerminationCommand的字段全爲空。我得到一個實例化的對象,但我發送的JSON沒有被填充到對象上。
爲什麼?
下面是輸出:
信息:運行終止:TerminateActorCommand {actorEid = NULL,terminatorEid = NULL,原因= NULL,effectiveTerminationDate = NULL}
嗯,這很有趣。按照預期,我添加了註釋,沒有任何區別。我添加了setters,並且使用了無參數構造函數。當我添加一個@JsonCreator構造函數像我的原始代碼並擺脫其他構造函數時,我得到'MessageBodyReader not found for media type = application/json'。我希望這個對象是不可變的。我怎麼做? – mikeb
構造函數上的'@ JsonCreator'註釋,沒有setter方法,是保持不變性的正確方法。你使用什麼版本的Jackson('jackson-core','jackson-annotations'和'jackson-databind')?你的項目是否包含獨立的Jackson配置文件? –
這是正確的,我沒有**需要擺脫默認的構造函數,只是創建了一個@JsonCreator標記的構造函數與我想設置的字段,它的工作原理。 – mikeb