44 thoughts on “REST Web Services 18 – Returning JSON Response

  1. I am having lots of problems in doing the same thing for a nested json object that you have implemented for plain json object. Please please someone help me out for doing the same thing for nested json object. There is nothing I got on internet about this problem.

  2. SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<com.vishal.model.Message>.

    Getting This Error, When returning Json Response…

  3. Latest Update for Adding dependency for Jersey Media Moxy-2.16

    please add following dependency first-
    <dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.16</version>
    </dependency>

    Then also if you are getting error then do this –
    Right click on the maven project in Eclipse -> Maven -> Update Project -> Check "Force update of snapshots/Releases" check box.

    Save and run again you will be happy to see response coming in JSON..?

  4. Thanks Koushik.
    Hi everybody, I am facing the "Internal Server Error" when I use @Produces(MediaType.APPLICATION_JSON), but its working fine for @Produces(MediaType.TEXT_XML). Un commented the dependencies
    <dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    </dependency>

    Please help me to resolve the issue, Thanks in advance!

  5. Hi after uncommenting jersey moxy in pom.xml i am getting this error MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<org.restexample.rst.Message> and 500 internal server error i am using moxy 2.23.2. any help please. The xml output is working fine

  6. really nice tutorial , easy to catch everything..

    does any one know the solution of this:

    i does not use maven then, how can convert rest api response as JSON using java? any thing to do in web.xml

  7. After uncommenting the json moxy got this error:
    SEVERE: Servlet [Jersey Web Application] in web application [/messenger] threw load() exception
    java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1332)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1102)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

  8. Hey man. Up until now, and still, a really good tutorial serie. But when I change @Produces to APPLICATION_XML to APPLICATION_JSON GlassFish responds with:

    Info: Loading application [messenger] at [/messenger]
    Info: messenger was successfully deployed in 2.225 milliseconds.
    Warning: StandardWrapperValve[Jersey Web Application]: Servlet.service() for servlet Jersey Web Application threw exception
    java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:257)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:208)
    at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:587)
    at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

    I'm not sure what I did wrong. Maybe you, or anyone else, have experienced something similar?

    Yours kindly, Heini

  9. Can someone please help!! I am facing issues with JSON conversion. I have included the Moxy jar still getting error as it does not convert to json and gives error.

    To confirm I am using JBoss as the application server and not Tomcat.

    My Rest Class has this function:
    //using Moxy api to convert to json
    @GET
    @Path("/AllUserDetailsJson")
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> getAllUserDetailsJson()
    {
    logger.info("Inside Rest getAllUserDetails json");
    List<String> l = new ArrayList<String>();
    l.add("Hello");
    l.add("You");
    return l;
    }

    Pom.xml :

    <dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.22.2</version>
    </dependency>

  10. @RequestMapping(value = "/getList", method = RequestMethod.GET, produces= { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public RegistrationDTO getUserAllList()
    {
    List<RegistrationDTO> greetingFodrm = registerService.getAllList();
    RegistrationDTO getEmployee = new RegistrationDTO();
    for (RegistrationDTO employeelist : greetingFodrm) {
    getEmployee.setFirstName(employeelist.getFirstName());
    getEmployee.setFirstName(employeelist.getLastName());
    getEmployee.setEmpCode(employeelist.getEmpCode());
    }
    System.out.println(getEmployee.getFirstName());
    return getEmployee;

    }
    Hi koushik, the above one is my code when i return josn format it wont get returned. can you please help me. What should i do?

  11. Using Maven/Eclipse/WebLogic 12.1.3 I started getting java linkage errors when I uncommented out the Moxy in the Pom.xml during deployment.  Tried changes to the build configuration including changes to the weblogic.xml to no avail.   Changed the dependency to Jackson and then the deployment worked.  <dependency>     <groupId>org.glassfish.jersey.media</groupId>
         <artifactId>jersey-media-json-jackson</artifactId></dependency>

  12. Hey. Can you please help me in this tutorial. I have done everything which you done in previous lecture and all runs very well but i am stuck in this tutorial it shows me error when i uncomment the moxy in pom.xml. and shows me multiple error of thread, threadpool and more.. Plz help me. Thanks.

  13. I'm having this error:

    java.lang.NoClassDefFoundError: org/glassfish/jersey/moxy/json/internal/ConfigurableMoxyJsonProvider

    That class is from moxy JAR which is in my build path and verified this class is in the JAR

  14. Using Maven/Eclipse/Tomcat 7  to add scope element to the jersey-media-moxy element and then add a dependency for jersey-entity-filtering to get the JSON response to work…………………………………<dependency>     <groupId>org.glassfish.jersey.media</groupId>
         <artifactId>jersey-media-moxy</artifactId>    <scope>runtime</scope>
     </dependency>
     <dependency>
              <groupId>org.glassfish.jersey.ext</groupId>         <artifactId>jersey-entity-filtering</artifactId>
            <scope>runtime</scope>
     </dependency>

  15. I am using jersey1.2 versions of jar where to do the conversion from json to java object in request and vice-versa while returning response , i have used MessageBodyReader and MessageBodyWriter. With jersey 1.2 version which moxy version would work? Also is there any other way of automatic conversion?

  16. i want to get output in the following manner: { 'employee' :[{"desig":"Consultant","id":5,"name":"Hamza"},{"desig":"Consultant","id":8,"name":"Deepak"}
    }] }.
    I want to consume the response using Angular JS. Please guide me through.

  17. Once I added moxy dependency, I am getting these exceptions in server logs.
    Servlet [Jersey Web Application] in web application [/messanger] threw load() exception
    java.lang.ClassNotFoundException: org.glassfish.jersey.message.filtering.EntityFilteringFeature
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1332)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
    at org.glassfish.jersey.moxy.json.MoxyJsonFeature.configure(MoxyJsonFeature.java:88)
    at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:712)
    at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:642)
    at org.glassfish.jersey.server.ResourceConfig.configureMetaProviders(ResourceConfig.java:810)
    at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:392)
    at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:166)
    at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:327)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:324)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:336)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
    at java.lang.Thread.run(Thread.java:745)

    anyone experiencing the same. Please help

  18. Hi Your tutorials are excellent. However after I follow this video on returning JSON response  I get this error — Malformed JSON: Unexpected '<'
    I can get the XML response without any problems, only get the error with JSON. Can you perhaps give some advice?

  19. Hello Koushik, 1st of all thank for such great videos. I have been following your tutorial since last 4 months and it's great Learning. 

    Please help me out on below:
    Imminently after "uncomment this to get JSON support" of E:MyStudyRestWebService_wsmessangerpom.xml Tomcat throwing too many error and warring such as below:

    WARNING: Failed to scan JAR [file:/E:/MyStudy/RestWebService_02/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/facebook/WEB-INF/lib/org.eclipse.persistence.core-2.5.0.jar] from WEB-INF/lib
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:220)

    Aug 23, 2015 3:05:55 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
    SEVERE: contextConfig.jarFile
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)

  20. Hi Team, 

    Thanks for this wonderful tutorial. I've been a great fan of Koushik and his way of teaching. 

    One query : post un-commenting the 'jersey-media-moxy' jar from pom.xml , maven in my work space is throwing a lot of maven dependency errors(approximately 17 failed to read artifact descriptors). Please help.

  21. There no one in youtube who've got better tutorials than yours. I can bet $100 on that. I have learned Spring, SOAP services and now REST from you. May god Bless you.

  22. Tutorials are tailor made for beginners. One query though is that why is that we need to annotate @XmlRootElement in the models while considering JSON payload? I tried to remove that annotation and it still worked for JSON payloads…

Leave a Reply

Your email address will not be published. Required fields are marked *