restful webservice in java and mysql - java

I am new to the restful webservices. I am new creating restful webservice in java using jersey . This webservice is getting data from mysql database and should display the response in xml..
But i am always getting the response error 500 from apache tomcat 7. In the console no error or exception is shown except the println method is diplaying the strings passed to it..but server is giving 500 error.. Please help me
userData.java
package com.userdb;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class userData {
public String name;
public int iduser;
public userData(){}
public userData(String name, int iduser) {
this.name = name;
this.iduser = iduser;
}
public String getName() {
return name;
}
public int getIduser() {
return iduser;
}
public void setName(String name) {
this.name = name;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
}
airtime.java
package com.userdb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/resttest")
public class airtime {
ResultSet rs=null;
String msg="hello";
Connection con=null;
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/get_users")
public List<userData> get_users(){
List<userData> retUser=new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
System.out.println("DriveManager");
PreparedStatement ps=con.prepareStatement("SELECT * FROM users");
rs=ps.executeQuery();
System.out.println(rs);
while(rs.next()){
userData obj=new userData();
obj.setIduser(rs.getInt("iduser"));
obj.setName(rs.getString("name"));
retUser.add(obj);
System.out.println("userData obj added to list");
}
con.close();
} catch (Exception e){
e.printStackTrace();
}
return retUser;
}
}
web.xml
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>userdb</display-name>
<servlet>
<servlet-name>Jersey WebService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.userdb</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey WebService</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>

Solution 1:
Adjust the top of userData.java to contain the following lines at the top your file:
package com.userdb;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public class userData
{...}
Explanation: You will notice that an XmlAccessorType annotation and an XMLAccessType has been added. This configuration is required when using setters in your object. You will notice that adjusting the code to not use setters (with the above excluded) will also allow you to view your RESTful service in a browser.
Solution 2:
A quicker alternative, is to set your public variables name and iduser to private. This will also avoid the clash when mapping to xml.

There should be a warning something like "...messagebodywriter not found for media type=application/xml ...".
The possible cause may be that you didn't include this dependency.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.21.1</version>
</dependency>
this is my workable pom dependencies
<dependencies>
<!-- jersey dependency -->
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to json -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to xml -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.21.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>stax2-api</artifactId>
<version>3.1.4</version>
</dependency>
</dependencies>
a workable web.xml
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Rest</display-name>
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.blithe.resource</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.scanning.recursive</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
workable resource
package com.blithe.resource;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.blithe.model.User;
#Path("helloworld")
public class HelloWorldResource
{
#GET
#Produces(MediaType.APPLICATION_XML)
public List<User> getStringArray(){
List<User> list = new ArrayList<>();
User u = new User();
u.setName("testName");
list.add(u);
return list;
}
}
and the model
package com.blithe.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope this will help you.
By the way, it is better not to include too many dependencies which might duplicate in your pom.xml, since some of them might conflict to each other. And it will cost a lot of time on debugging. So it's better to find out what dependencies are really needed.
Cheers!
Gregory Nikitas is right. The issue in your model class should also be taken care of.

Related

a strange name next to the webapp name shown in eclipse server tab

My pom is as follow:
<modelVersion>4.0.0</modelVersion>
<groupId>net.codejava</groupId>
<artifactId>EhrmsWs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
and in eclipse,web project settings, context root is
EhrmsWs
but when I add this webapp to wildfly runtime, there is a name
MyWebsite-0.0.1-SNAPSHOT.war
where does this name come from and what does it represents?
my context root is still
http://127.0.0.1:8080/EhrmsWs
?
the application is a simple web service example, I access using postman, request is
http://127.0.0.1:8080/EhrmsWs/rest/products/
but it returns 404 - Not Found, why?
the web.xml setting is as follow:
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>EhrmsWs</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>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>net.codejava.ws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
the service class is as follow:
package net.codejava.ws;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/products")
public class ProductResource {
private ProductDAO dao = ProductDAO.getInstance();
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response list() {
List<Product> listProducts = dao.listAll();
if (listProducts.isEmpty()) {
return Response.noContent().build();
}
return Response.ok(listProducts).build();
}
//.....
}
[Edit on 20220816]
Now the request
http://localhost:8080/EhrmsWs/rest/products
can pass to resource ProductResource.java, but I write a similar resource TrainingHist.java with similar method as follow:
package net.codejava.ws;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/trainingHist")
public class TrainingHistResource {
private TrainingHistDAO dao = TrainingHistDAO.getInstance();
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response list() {
List<TrainingHist> listTrainingHists = dao.listAll();
if (listTrainingHists.isEmpty()) {
return Response.noContent().build();
}
return Response.ok(listTrainingHists).build();
}
}
then I send the get request
http://localhost:8080/EhrmsWs/rest/trainingHist
but it returns 404 not found, why?

Unable to test restful service

I am very new to Restful Services and I followed some guidelines given be the boss to make it. When I am using the URL to test it via browser, it shows not found. Console is not showing any error or exception (However, I removed almost 100 errors to reach this point), but still the result is same.
This is my directory structure
This is my RDRresource.java (Includes the service I want to test)
package org.uclab.IMP.rs.rdr;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.IMP.*;
import com.google.gson.Gson;
import org.uclab.IMP.datamodel.*;
import org.uclab.IMP.datamodel.RDR.*;
import org.uclab.IMP.datamodel.RDR.dataadapter.*;
/**
* Facade for the Restful Web service to handle the data curation functions
*/
#Path("rdr")
public class RDRresource {
#Context
private UriInfo context;
/**
* Creates a new instance of DataCurationResource
*/
public RDRresource() {
}
private static final Logger logger = LoggerFactory.getLogger(RDRresource.class);
/**
* This function is using to get user by ID
* #param UserID
* #return a list of object Users with "Error", "No Error" and new added ID
*/
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("RetriveRules")
public List<Rules> RetriveRules() {
Rules objOuterRules = new Rules();
List<Rules> objListRules = new ArrayList<Rules>();
try
{
objOuterRules.setRuleID(Long.parseLong("RuleID"));
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
objListRules = objADBridge.RetriveRules();
logger.info("Get all rules successfully, rules Details="+objOuterRules);
}
catch(Exception ex)
{
logger.info("Error in getting user");
}
return objListRules;
}
This is my web.xml file
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.uclab.IMP.rs.rdr</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
</web-app>
URL I am trying and result is here

REST API is unable to work in JSON format

I am new to developing REST API with Java. I made a very simple one using the mkyong tutorials, where it only says "hello". I am using Apache Tomcat.
Now I am trying to develop a one where it will return the JSON objects. I am attempting the example here - http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/. Some of the code are changed (ex: package name).Below is my code.
Track.java
package com.tutorialspoint;
/**
*
* #author Yohan
*/
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
#Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
JsonService.java
package com.tutorialspoint;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* #author Yohan
*/
#Path("/json/metallica")
public class JsonService {
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.tutorialspoint</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
My application is not a marven project. So the added libraries are below.
I tested the application with the below URL.
http://localhost:8080/RESTFUL_API_SAMPLE/rest/json/metallica/get
All I got is the below page
Any idea about why I am not getting the expected result?
Currently you don't have any JSON/POJO support. The jersey-json jar and the POJOMappingFeature configuration in your web.xml is for Jersey 1.x, which won't work for Jersey 2.x. For all the jars you need for Jersey 2.x support, see this answer.

javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: JSON support in Java REST Webservices with Jersey

Okay, this question has probably been asked before, but on all sites I've looked the explanation on "how to do this" tells me I'm doing it completely right.
I know I'm not, as I get a 500 server error on my localhost tomcat and I get the following error in my server logs:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.myapp.domain.Location, and Java type class com.myapp.domain.Location, and MIME media type application/json was not found
So, what I'm trying to do is to develop a RESTful web service with Jersey (in Java). Everything is going fine, except for the fact that I want to return JSON. I can't find what I'm doing different from these people:
How to send response as JSON in Jersey Rest
http://www.jasonwhaley.com/blog/2011/01/18/multiple-content-types-in-jax-rs/
https://github.com/jasonray/jersey-starterkit/wiki/Serializing-a-POJO-to-xml-or-json-using-JAXB
https://github.com/jasonray/jersey-starterkit/wiki/Serializing-a-POJO-to-json-using-built-in-jersey-support
http://www.vogella.com/tutorials/REST/article.html
My POJO (Location) looks like this:
package com.myapp.domain;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement()
public class Location {
private int id;
private double longtitude;
private double latitude;
public Location() {
new Location(-1, -1, -1);
}
public Location(double longtitude, double latitude) {
new Location(-1, longtitude, latitude);
}
public Location(int id, double longtitude, double latitude) {
this.id = id;
this.longtitude = longtitude;
this.latitude = latitude;
}
public void setID(int id) {
this.id = id;
}
public void setLongtitude(double longtitude) {
this.longtitude = longtitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public int getID() {
return this.id;
}
public double getLongtitude() {
return this.longtitude;
}
public double getLatitude() {
return this.latitude;
}
}
My resource looks like this:
package com.myapp.MyAPP;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.myapp.domain.Location;
#Path("Locations")
public class LocationInfo {
#GET
#Path("/get/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Location getLocation(#PathParam("id") int id) {
Location loc = new Location(3, 4.007391, 51.00237);
return loc;
}
}
And this is my web.xml:
<?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>MyAPP</display-name>
<servlet>
<servlet-name>MyAPP REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.myapp.MyAPP</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyAPP REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I've got these libraries included: asm-3.1.jar, jersey-client-1.17.1.jar, jersey-core-1.17.1.jar, jersey-json-1.17.1.jar, jersey-server-1.17.1.jar, jersey-servlet-1.17.jar, jsr11-api-1.1.1.jar
The one who sees what I'm not seeing gets a beer. Or at least my eternal gratitude, cause I've been looking at this for way too long and I still can't see it.
Okay, so I turned out orid had the right answer: I simply needed to add some extra libraries!
I probably overlooked it or most tutorials probably suppose you add all the libraries you download with jersey straight away...
So this fixed the problem: adding
jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
Thanks again to orid, you just saved my weekend.

Jersey 2.0 equivalent to POJOMappingFeature

I have some experience using Jersey < 2.0. Now I am trying to build a war application to provide a JSON Webservice API.
I am now struggling for a considerable amount of time trying to configure Moxy and it seams to be way more complicated than what was adding
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
to your web.xml back in Jersey < 2.0.
Is there some possibility to just say "please add json support"?
Currently I just get a lot of Internal Server Error errors without any log entries on the server and just think "I have to do something totally wrong, this can't be so hard"
Can anyone give me a hint?
Please use the below dependency which will do it automatically for you.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>
If you want to define it in your web.xml file then:
JACKSON:
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
</init-param>
MOXY
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.moxy.json.MoxyFeature</param-value>
</init-param>
And if using maven add the following dependency to your pom file
JACKSON
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>your jersey version</version>
</dependency>
MOXY
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>your jersey version</version>
</dependency>
You can configure EclipseLink MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class.
Example #1
package org.example;
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class CustomerApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(2);
set.add(MOXyJsonProvider.class);
set.add(CustomerService.class);
return set;
}
}
Example #2
package org.example;
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class CustomerApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(1);
set.add(ExampleService.class);
return set;
}
#Override
public Set<Object> getSingletons() {
MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
moxyJsonProvider.setAttributePrefix("#");
moxyJsonProvider.setFormattedOutput(true);
moxyJsonProvider.setIncludeRoot(true);
moxyJsonProvider.setMarshalEmptyCollections(false);
moxyJsonProvider.setValueWrapper("$");
Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1);
namespacePrefixMapper.put("http://www.example.org/customer", "cust");
moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper);
moxyJsonProvider.setNamespaceSeparator(':');
HashSet<Object> set = new HashSet<Object>(1);
set.add(moxyJsonProvider);
return set;
}
}
For More Information
http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html
ACtually, it just worked for me, with the PojoMappingFeature param omitted.
Going to:
http://localhost:8080/webapi/myresource/complexObject/foo
yields this json:
{"name":"foo","value1":1374185178829,"value2":42}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
entry point:
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
#Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
#Path( "complexObject/{name}" )
#GET
#Produces( { MediaType.APPLICATION_JSON } )
public ComplexObject complexObject( #PathParam( "name" ) String name ) {
return new ComplexObject(name, System.currentTimeMillis(), 42L);
}
}
bean to jsonize:
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
#Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
#Path( "complexObject/{name}" )
#GET
#Produces( { MediaType.APPLICATION_JSON } )
public ComplexObject complexObject( #PathParam( "name" ) String name ) {
return new ComplexObject(name, System.currentTimeMillis(), 42L);
}
}
Found this as well working, and was the easiest in resolving the problem (AFAIT)
Include the below dependency in your pom.xml / include the respective JAR file in lib path
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency
Link here
Just use #XmlElement in place of #XmlAttribute (only attribute receives # prefix, possibly restart your appserver for changed effect!)

Categories