简体   繁体   中英

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 ie 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

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

private ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.convertValue(YOUR POJO CLASS, JsonNode.class);

You can use Jackson and achieve this as above. GSON also does the job.

The way I use is with Google's Gson library. Very simple and powerful

Spring and Jackson as it is so simple. You can find a very basic example below Jackson/spring JSON example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM