Search code examples
javajsonhibernatepojo

Creating json object from POJO object in restful web service


I am developing a web application. I have database used by the web service. I want to send the same data to the web pages which are calling web service.

I get the data i.e. single row from the database by using hibernate and POJO classes(getColumn). Now I have object(POJO class) of the Table which represent single row of the database. For sending it back to the web pages (html, jsp), I need to convert it to the json object as my web service returns the json object.

How can I make Json object from POJO classes. There are many other ways to generate Json String but i want json object. How can do this?

Thank you


Solution

  • You can use GSon to convert json object to java object

    Link to refer example.

    Gson gson = new Gson();
    //to get json object use toJson
    String json = gson.toJson(obj);
    //to get java object use fromJson
    MyClass obj = gson.fromJson(jsonObj, MyClass.class);
    

    or

    jackson is also pretty fast and easy to use