用 json-simple 在 java 中做 POST

Do POST in java with json-simple

我有一个 REST 服务,我想用 JSON 做一个 POST 查询,但它不工作。

下面是我的其他查询的示例,它运行正常:

@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"}}

这是 DAO 用于: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"}}

但是没有成功。

你可以试试这个:

@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveNewPerson(Person person){
//...
}

Please see section 5 on this page.