【问题标题】:Do POST in java with json-simple使用 json-simple 在 java 中进行 POST
【发布时间】:2015-04-16 19:52:04
【问题描述】:

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

但还是不行。

【问题讨论】:

    标签: java json rest post server


    【解决方案1】:

    你可以试试这个:

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

    Please see section 5 on this page.

    【讨论】:

    • 非常感谢,如果我使用 Java、Maven、TomCat、MySql、Hibernate,如何在没有球衣的情况下发帖
    • 无论如何您都需要一个 JAX-RS (REST) 实现,因为您的代码想要使用 REST API。 Tomcat 没有内置的 REST 实现,因此您必须部署一个。 Jersey 是一种 REST 实现(默认实现),因此非常适合在 Tomcat 下部署。您可以查看此页面如何在您的战争中部署 Jersey:laszlo.gazsi.net/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2014-10-11
    相关资源
    最近更新 更多