使用json-simple在java中进行POST

时间:2015-04-16 19:52:04

标签: java json rest post server

我有一个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

的DAO
    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"}}

但它没有成功。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

Please see section 5 on this page.