We will need a couple of more jars in our classpath in order to use JSON.
They are - jackson-core-asl-1.8.0.jar, jackson-jaxrs-1.8.0.jar, jackson-mapper-asl-1.8.0.jar, jackson-xc-1.8.0.jar, jersey-json-1.8.jar, jersey-bundle-1.8.jar
Download them & add in the class path or add them in pom.xml as a dependency.
Here is the code snippet for the web service which returns JSON Object
They are - jackson-core-asl-1.8.0.jar, jackson-jaxrs-1.8.0.jar, jackson-mapper-asl-1.8.0.jar, jackson-xc-1.8.0.jar, jersey-json-1.8.jar, jersey-bundle-1.8.jar
Download them & add in the class path or add them in pom.xml as a dependency.
Here is the code snippet for the web service which returns JSON Object
@GET
@Path("/json")
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUserDetailsInJsonFromURL
(@QueryParam("name") String name) {
User returnUser = new User();
List<User> returnList = new ArrayList<User>();
if (name != null && !"".equals(name)) {
for (int count = 0; count < userList.size(); count++) {
if (name.equalsIgnoreCase(userList.get(count).getName())) {
returnUser = userList.get(count);
returnList.add(returnUser);
}
}
}
return returnList;
}
note: userList is the list which contains the all the user data fetched from database.
And, here is the client which accepts & then processes the JSON result set
(Client needs java-json.jar in it's classpath to develop this code)
And, here is the client which accepts & then processes the JSON result set
(Client needs java-json.jar in it's classpath to develop this code)
public void parseJson(WebResource service)
throws UniformInterfaceException, JSONException {
JSONArray resultArray = new JSONArray(service
.path("resources/test/json/Tom")
.get(String.class));
List<User> userList = new ArrayList<User>();
for (int count = 0; count < resultArray.length(); count++) {
JSONObject userObject = resultArray.getJSONObject(count);
User user = new User(userObject.get("name").toString(), userObject
.get("surname").toString(),
userObject.get("address")
.toString());
userList.add(user);
}
System.out.println(userList);
}
Feel free to share!!
Related post -
Creating RESTful web service with Maven & Jersey
Creating a Simple Web Service Client
"Perplexity is the beginning of the knowledge" - Khalil Gibran
Related post -
Creating RESTful web service with Maven & Jersey
Creating a Simple Web Service Client
"Perplexity is the beginning of the knowledge" - Khalil Gibran
No comments :
Post a Comment