RESTful Web Services JSON API Transformer with Java
Wall Script
Wall Script
Monday, October 08, 2012

RESTful Web Services JSON API Transformer with Java

This post is the continuation of my previous last post, I had explained how to create a basic RESTful web services API using Java, now I want to explain JSON transformer to work with input Get and Post methods parameters. Just added a new class called transformer it converts object data into JSON text output format.

RESTful Web Services with input parameters

Download War File    Download Project Source

Database
Sample database messages table contains three columns msg_id, message and user_id_fk.
CREATE TABLE  `messages` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`message` TEXT,
`user_id_fk` INT,
PRIMARY KEY (`msg_id`)
);

This tutorial required RESTful service support JAR files jersey-client-1.0.3.jar, jersey-core-1.0.3.jar, jersey-server-1.0.3.jar(Download), jsr311-api-1.0.jar(Download) and asm-3.1.jar(Download). Copy these files into WEB-INF -> lib

RESTful Web Services using Java and MySQL

Download Project Source link contains all these JARs.

Previous Tutorials: Java MySQL Insert Record using Jquery. and Java MySQL JSON Display Records using Jquery.

Package structure for more details please check my previous java tutorials.
RESTful Web Services using Java and MySQL

FeedObjects.java
Create a new package called dto (Data Transaction Objects). Created transaction objects title, description and url.
package dto;

public class FeedObjects {

private String msg_id;
private String message;
private String user_id;

//Generate Getters and Setters
}
Explained generating Getters and Setter methods in this following tutorialJava MySQL JSON Display Records using Jquery.

Project.java
Create a dao(Data Access Object) method GetFeeds with Arraylist datatype, using select statement getting results from messageses table where user_id_fk. Binding results into feedData object.
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import dto.FeedObjects;

public class Project
{
public ArrayList<feedobjects> GetFeeds(Connection connection,,String User_ID) throws Exception
{
ArrayList<feedobjects> feedData = new ArrayList<feedobjects>();
try
{
PreparedStatement ps = connection.prepareStatement("SELECT msg_id,message,user_id_fk FROM messages WHERE user_id_fk=? ORDER BY msg_id DESC");
ps.setString(1,User_ID);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
FeedObjects feedObject = new FeedObjects();
feedObject.setTitle(rs.getString("msg_id"));
feedObject.setDescription(rs.getString("message"));
feedObject.setUrl(rs.getString("user_id_fk"));
feedData.add(feedObject);
}
return feedData;
}
catch(Exception e)
{
throw e;
}
}

}

ProjectManager.java
Model class write the business logic and data validation.
package model;

import java.sql.Connection;
import java.util.ArrayList;

import dao.Database;
import dao.Project;
import dto.FeedObjects;

public class ProjectManager {

public ArrayList<feedobjects> GetFeeds(String User_Id)throws Exception {
ArrayList<feedobjects> feeds = null;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
Project project= new Project();
feeds=project.GetFeeds(connection,User_Id);
}
catch (Exception e) {
throw e;
}
return feeds;
}

}

FeedTransformer.java
Transformer class converts Java object result into JSON text format.
package transformer;

import java.util.ArrayList;
import com.google.gson.Gson;

import dto.FeedObjects;

public class FeedTransformer
{
public static String UserFeed(ArrayList<FeedObjects> feedData)
{
String feeds = null;
Gson gson = new Gson();
feeds = gson.toJson(feedData);
return feeds;
}
}

FeedService.java
Web Services class for RESTful API.
package webService;

import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;

@Path("/WebService")
public class FeedService {

@GET
@Path("/GetFeeds")
@Produces("application/json")
public String messageFeed(@QueryParam("userId") String User_Id)
{
String feeds = null;
try
{
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds(User_Id);
feeds=FeedTransformer.UserFeed(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console 
}
return feeds;
}

}

If you want to convert GET to POST just do little change.

import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
to
import javax.ws.rs.POST;
import javax.ws.rs.FormParam;

@GET
@Path("/GetFeeds")
to
@POST
@Path("/GetFeeds")


public String messageFeed(@QueryParam("userId") String User_Id)
to
public String messageFeed(@FormParam("userId") String User_Id)


You can test post method with Mozilla Firefox Add on Poster.

RESTful Web Services with input parameters


web.xml
The URL configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FirstProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>
com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>

Final GET URL
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds

Here RESTfulProject is the project name, REST is the web.xml servelt mapping name, WebService is REST API path and GetFeeds is the method name.

Note: For checking POST URLs user Poster extension for Chrome and Firefox.

JSON Output
[{
"msg_id":"3",
"message":"Everything is possible. ",
"user_id":"2"
},
{
"msg_id":"1",
"message":"Make People fall in love with Your Ideas",
"user_id":"2"
}]

Next post I will explain friendly RESTful web services with path inputs parameters.
web notification

30 comments:

  1. Wow!I like you Java tutorial.
    Do you know a good and cheap Java hosting.

    ReplyDelete
  2. nice post dudeee...................

    ReplyDelete
  3. Why not use out-of-the-box JSON conversion that Jersey does? Additional manual conversion to Strings is completely unnecessary in this example.

    ReplyDelete
  4. Very useful tutorial. But I can't find a cheap hosting with java activated

    ReplyDelete
  5. REST has had such a large impact on the Web that it has mostly displaced SOAP- and WSDL-based interface design because it's a considerably simpler style to use.

    ReplyDelete
  6. super explanation it is very helpful for me
    thank you

    ReplyDelete
  7. thanks for tutorial I have a question except this
    I have a webservice and it has a add method like below
    public Integer add(int a,int b){
    return a+b;
    }
    when I call this method and given (2,3) it return 5
    and convert json it produce "5" is this correct output?
    serviceAdd sAdd=new serviceAdd();

    Integer result=sAdd.add(2,3);

    Gson gson = new Gson();

    String json=gson.toJson(result);
    System.out.println(json);
    output is "5" is it correct result ?

    ReplyDelete
  8. Thank you Very much...
    I'am searching for this from two days and finally got it from you.
    I used this tutorial for accessing web services in Android.
    Thank You once again.....

    ReplyDelete
  9. i am new to service and webservice..how can i start to learn writing the services.Please help me

    ReplyDelete
  10. thnax it's very useful

    ReplyDelete
  11. how to created webservices?????
    please post the steps of creating webservices using same example in Net Beans IDEs.
    As soon as possible.

    ReplyDelete
  12. how to created websevices using posted example???
    Please post the steps of creating webservices.
    As soon as possible.

    ReplyDelete
  13. where did you passed the driver name and url for the connection??

    ReplyDelete
  14. Hi, everything works great!!! Great code. When I want to change GET to POST the code doesn't work, User_Id give me null value, can you help me.

    public String messageFeed(@FormParam("userId") String User_Id) {
    System.out.println("userID > "+User_Id);
    }

    RESULT
    userID > null

    ReplyDelete
  15. Thanks for posting man great tutorial

    ReplyDelete
  16. How provide authentication to restful service and also authenticate using jquery or javascript

    ReplyDelete
  17. When i validated this link "http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds" in json validator (http://jsonlint.com/) showing error...
    Can any let me know why??

    ReplyDelete
  18. thanks for post :)

    ReplyDelete
  19. how to pass javascript json variable in java restfull service..?

    ReplyDelete
  20. Hi,
    Thank you for this tutorial,

    If :
    Final GET URL
    http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
    .
    where the userId param come from ?
    Thanks

    ReplyDelete
  21. Its very useful to understand restful web service.

    Thanks

    ReplyDelete

  22. Very GOOD and understandable Tutorial

    *** I'm Getting this common :
    "SEVERE: The ResourceConfig instance does not contain any root resource classes"

    Already trying this fix i found on other post but it doesn't work.

    com.sun.jersey.config.property.packages
    org.arpit.javapostsforlearning.webservices


    === Please look my web.xml


    FirstProject

    index.html
    index.htm
    index.jsp


    ServletAdaptor

    com.sun.jersey.server.impl.container.servlet.ServletAdaptor


    com.sun.jersey.config.property.packages
    vpsolucoes.htmlreader.service

    1


    ServletAdaptor
    /REST/*

    </web-app

    ReplyDelete
  23. Hi srinivas, I am trying to develop java code for searching the bugs in bugzilla using bugzilla rest api method(/search) the link for bugzilla rest api method is https://wiki.mozilla.org/Bugzilla:REST_API:Methods#Search_for_bugs_.28.2Fbug_GET.29. Can you let me know how can i develop java code for searching bugs with description as parameter.

    ReplyDelete
  24. Hi,
    This is very useful for all.Thanks lot....
    Final GET URL
    http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds

    The json result is not coming in browser panel, displaying only console.
    How to get it in browser?

    ReplyDelete

  25. Please write one restful service to upload a file containing data to import into mysql server.

    ReplyDelete

mailxengine Youtueb channel
Make in India
X