我有一个REST
服务,我想要POST
进行JSON
查询,但它不起作用。
以下是我的其他查询的示例:
@GET
@Path("/getByIdJSON/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Person getPersonByIdJSON(@PathParam("id") int id) {
return personDao.getById(id);
}
以上查询给出了以下来自服务器的响应:
{"person":{"id":11,"fullName":"Maria","age":19,"city":"Tver","gender":"female"}}
这是:getPersonByIdJSON
public Person getById(int id) {
Person person = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
person = (Person) session.createQuery("from Person p where p.id = :ID").setParameter("ID", id).uniqueResult();
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
} finally {
if (session != null) {
session.close();
}
}
return person;
}
对于POST
我这样做:
@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
public String saveNewPerson(JSONObject person) throws JSONException {
JSONObject obj = new JSONObject();
obj.put("fullName",new String());
obj.put("age",new String());
obj.put("city",new String());
obj.put("gender",new String());
person.put("person", obj);
if (!personDao.savePerson(person)) {
return "Person create success id=";
}
else {
return "error, check information for new person";
}
}
和DAO:
public boolean savePerson(JSONObject person) {
Session session = null;
boolean hasErrors = false;
try {
session = sessionFactory.openSession();
session.beginTransaction();
session.saveOrUpdate(person);
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
hasErrors = true;
} finally {
if (session != null) {
session.close();
}
}
return hasErrors;
}
现在,要添加新人,我已发送到服务器POST query
( 通过RestEasy )并在正文中写下:
{"person":{"fullName":"newperson","age":19,"city":"exampleCity","gender":"female"}}
但它没有成功。
答案 0 :(得分:0)
你可以试试这个:
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveNewPerson(Person person){
//...
}