我想通过POST请求将序列化对象发送到服务器。
Paint paint = new Paint();
paint.setYear(2010);
paint.setTitle("title");
JAXBContext jc = JAXBContext.newInstance(Paint.class, Art.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
java.io.StringWriter sw = new StringWriter();
marshaller.marshal(paint, sw);
ClientRequest request = new ClientRequest("http://localhost:8080/rest/createArt");
request.body("application/xml", sw.toString());
ClientResponse<Response> response = request.post(Response.class);
对于这项简单的服务:
@POST
@Path("/createArt")
@Consumes("application/xml")
public Response createArt(Art a){
artDAO.createArt(a);
return Response.ok(a).build();
}
但是我收到以下错误:
DefaultClientConnection:249 - Receiving response: HTTP/1.1 400 javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"paint"). Expected elements are <{}art>, <{}photo>
为什么这些课程?
Art.java:抽象类
@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@XmlRootElement(name = "art")
public abstract class Art {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToMany (mappedBy="art",cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Photo> photo;
...
}
Paint.java:继承自Art
@Entity
@XmlRootElement(name = "paint")
public class Paint extends Art{
@Enumerated(EnumType.STRING)
private SupportArt support;
@Enumerated(EnumType.STRING)
private Realisation realisation;
...
}
Photo.java
@Entity
@XmlRootElement(name = "photo")
public class Photo {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn (name="art_id")
private Art art;
private String path;
...
}
我不明白我的错误,我认为这是JAXB注释的问题。 继承也给我带来了一些麻烦。 Photo和Art之间存在双向关系,当我删除它时,照片不再是预期的元素(它持续&lt; {} art&gt;)。
我在网上搜索并尝试了很多东西,但它没有解决我的问题。
答案 0 :(得分:1)
我发现了我的错误,我只需要使用XmlSeeAlso:
Art.java:抽象类
@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@XmlSeeAlso(Paint.class)
public abstract class Art {
也必须修改这一行:
ClientResponse<String> response = request.post(String.class);