当我尝试使用POST向我的Jersey REST服务传递JSON字符串时,REST客户端返回415 - 不支持的媒体类型。通过GET查询资源工作正常。杰克逊不会将JSON字符串序列化为Java对象
实体类:
@Entity
public class Agent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Agent() {
}
public Agent(String name) {
this.name = name;
}
@OneToMany(mappedBy = "agent", cascade = CascadeType.PERSIST)
@JsonBackReference
private List<Action> actions = new ArrayList<>();
//...getter/setter...
}
服务类REST:
@Path("/agents")
public class AgentService {
private static PersistenceFacade f = new PersistenceFacade();
private static StatusFacade s = new StatusFacade();
//GET all Agents
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Agent> getAllAgents() {
return f.getAllAgents();
}
@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void postAgent(Agent a) {
f.createAgent(a);
}
}
PersistenceFacade
public class PersistenceFacade {
//EMF als zentraler Handler für alle EM
private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("simulationPU");
public void createAgent(Agent a) {
EntityManager em = factory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(a);
tx.commit();
}
public List<Agent> getAllAgents() {
EntityManager em = factory.createEntityManager();
Query q = em.createQuery("SELECT a FROM Agent a");
List<Agent> aList = q.getResultList();
return aList;
}
传递GET请求来http://localhost:8080/simulation_api/agents回报我TESTDATA:
[{"id":2104,"name":"pi3"},{"id":2107,"name":"pi4"}]
但是,当我尝试使用POST将JSON字符串传递到http://localhost:8080/simulation_api/agents/create时,如上所述发生错误(HTTP响应415)。我把要求的身体内:
{"id":2804,"name":"pi7"}
可能是什么问题?没有抛出异常......
你是否包括“内容类型:应用程序/ JSON的”头在你的POST请求? –