The Jetty server is unable to provide JSON responses

Whenever I use the command mvn jetty:run to initiate my server, it fails to return JSON formatted strings. Instead, it only returns raw strings or "null" for all objects.

In the code snippet for my endpoint, you can observe that there is no variation in returning a string wrapped inside an object versus returning it as a raw string.

 @Path("/snapsono/")  
 public class RestEndPoint {  
     GeneralServer server = new GeneralImpl();  
     private Logger logger = Logger.getLogger("RestEndPoint");  
     @GET
     @Path("/hello")
     @Produces({MediaType.APPLICATION_JSON})
     public SnapString sayHello() throws Exception{
        logger.info("reach hello");
        SnapString snapString = new SnapString("hello");
        logger.info("this is: "+snapString.getString());
        return snapString;
     } 

     @GET
     @Path("/helloString")
     @Produces({MediaType.APPLICATION_JSON})
     public String sayHelloString() throws Exception{
        return "hello";
     }
   }

For the SnapString class, I have included the @XmlRootElement at the beginning of the class definition.

@XmlRootElement
public class SnapString {
    private String str = "";
    public SnapString(){
    }

    public SnapString(String str){
        this.str = str;
    }

    public String getString(){
        return this.str;
    } 
}

However, upon execution, I receive the following responses:

dilin-mbp:~ dilin$ curl -i -H "Accept: application/json" -H "Content-Type:  application/json" -X GET http://localhost:9090/snapsono/hello
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Server: Jetty(8.1.16.v20140903)

null

dilin-mbp:~ dilcurl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://localhost:9090/snapsono/helloString
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Server: Jetty(8.1.16.v20140903)

hello

dilin-mbp:~ dilin$

While returning a raw string works fine, returning an object in JSON format always results in null value. However, from the logs, it is evident that the returned object contains a value.

[INFO] Restart completed at Mon Feb 16 21:53:56 PST 2015
Feb 16, 2015 9:54:48 PM snap.sono.demo.rest.RestEndPoint sayHello
INFO: reach hello
Feb 16, 2015 9:54:48 PM snap.sono.demo.rest.RestEndPoint sayHello
INFO: this is: hello
Feb 16, 2015 9:57:45 PM snap.sono.demo.rest.RestEndPoint sayHello

Please review my simplistic approach based on the information provided by the two Info log statements.

The complete startup message for Jetty is as follows:

dilin-mbp:snapsono dilin$ mvn jetty:run
[INFO] Scanning for projects...
[WARNING] Failed to retrieve plugin descriptor for org.eclipse.jetty:jetty-  server:8.1.8.v20121106: Failed to parse plugin descriptor for   org.eclipse.jetty:jetty-server:8.1.8.v20121106      (/Users/dilin/.m2/repository/org/eclipse/jetty/jetty-server/8.1.8.v20121106/jetty-  server-8.1.8.v20121106.jar): No plugin descriptor found at META-     INF/maven/plugin.xml
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] Failed to retrieve plugin descriptor for org.eclipse.jetty:jetty-server:8.1.8.v20121106: Failed to parse plugin descriptor for org.eclipse.jetty:jetty-server:8.1.8.v20121106   (/Users/dilin/.m2/repository/org/eclipse/jetty/jetty-server/8.1.8.v20121106/jetty-  server-8.1.8.v20121106.jar): No plugin descriptor found at META-  INF/maven/plugin.xml
[INFO]
[INFO] >>> jetty-maven-plugin:8.1.8.v20121106:run (default-cli) > test-compile @ Sproject >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Sproject ---
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/dilin/Documents/workspace/snapsono/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ Sproject ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Sproject ---
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/dilin/Documents/workspace/snapsono/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ Sproject ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< jetty-maven-plugin:8.1.8.v20121106:run (default-cli) < test-compile @ Sproject <<<
[INFO]
[INFO] --- jetty-maven-plugin:8.1.8.v20121106:run (default-cli) @ Sproject ---
[INFO] Configuring Jetty for project: Sproject
[INFO] webAppSourceDirectory not set. Defaulting to /Users/dilin/Documents/workspace/snapsono/src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = /Users/dilin/Documents/workspace/snapsono/target/classes
[INFO] Context path = /
[INFO] Tmp directory = /Users/dilin/Documents/workspace/snapsono/target/tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file =     file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = /Users/dilin/Documents/workspace/snapsono/src/main/webapp
2015-02-16 22:00:01.766:INFO:oejs.Server:jetty-8.1.8.v20121106
2015-02-16 22:00:02.128:INFO:oejpw.PlusConfiguration:No Transaction manager found - if your webapp requires one, please configure one.
Null identity service, trying login service: null
Finding identity service: null
2015-02-16 22:00:03.549:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/},file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/
2015-02-16 22:00:03.549:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/},file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/
2015-02-16 22:00:03.549:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/},file:/Users/dilin/Documents/workspace/snapsono/src/main/webapp/
Feb 16, 2015 10:00:03 PM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
  snap.sono.demo.rest
Feb 16, 2015 10:00:03 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class snap.sono.demo.rest.RestEndPoint
Feb 16, 2015 10:00:03 PM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
  Feb 16, 2015 10:00:03 PM     com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM'
2015-02-16 22:00:04.040:INFO:oejs.AbstractConnector:Started       <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cc9fa9a0a9afb88fa4ada2a2a9a08fa3a2a2a9afb8a3be8cfce2fce2fce2fc">[email protected]</a>:9090
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 40 seconds.

Answer №1

Hooray! I've successfully resolved this problem.

Essentially, at the class level, we must annotate with @XmlRootElement.

Subsequently, for every returning attribute, we should annotate it with @XmlElement. This will allow the tagged member variables to be returned in JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Could not parse JSON after php file update. Everything was fine before switching to PDO, but now encountering a parsing issue

I encountered an issue where I could log in using a member from the database (MySQL) using Chrome, and create a new user successfully. However, when I tried to use the app, it crashed after attempting to create a new user. After testing some simple PHP co ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Guide on obtaining JSON data in an android application through a PHP file?

I am a beginner in Android development and I have recently created a simple data fetching application. However, I am facing an issue where I am only able to retrieve the value of one variable from my PHP file, even though both variables are present in the ...

How can PHP Curl be used to retrieve a corresponding value from a JSON data?

On my webpage, I have some jSON data that I need to gather into arrays using cURL in PHP code, not through the command line. The code snippet below shows how I currently achieve this: $token = 'my_token_here'; $headers = ['Authorization: B ...

If PHP does not return data in a JSON encoded format, Ajax will not function properly

I have a PHP script that returns an array if an error occurs, otherwise it returns a <DIV> if(!empty($error)) { $true = true; $res = array('info' => '$error', 'error' => '$true'); echo json_enc ...

Exploring the combination of search functionality using json and PHP language with SQL integration

I developed a search system with 4 pages/steps. The first 3 pages consist of checkboxes for filtering, and I am facing an issue with creating these checkboxes based on JSON data. Currently, I can only read the names from the JSON data to create the checkbo ...

Dealing with JSON variables in PHP and jQuery to obtain a string variable instead

Currently, I am retrieving a text from a php script via ajax using jquery. The code looks like this: $.ajax({ dataType: 'json', url: 'someURL.com', success:function(result){ json = ...

Having trouble locating the correct JSON array syntax for Highcharts

Hey there! I'm currently facing a bit of a challenge while trying to set up a JSON array using PHP and integrate it into Highcharts. Currently, I am creating the array in this manner: $stack[] = array($commname => $countit); $stack = json_encode( ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

How can I configure the dataSource using a JSON data feed in FuelUX Tree component?

I'm currently working on setting up a json data source for the FuelUX tree. To achieve this, I have created a PHP file that echoes a JSON encoded array which results in something like: [{"name":"South Africa","type":"folder","additionalParameters":{" ...

Ajax: client dilemma created by the interaction of two functions

My university homework assignment requires me to develop a small e-commerce website. After logging in, the user will be directed to the homepage where they will receive a JSON object from the server containing product information to dynamically generate th ...

Why is it important to incorporate depth in JSON encoding?

Take a look at this illustrative code: $array = array( 'GiamPy' => array( 'Age' => '18', 'Password' => array( 'password' => '1234&apo ...

Encountering an issue when attempting to save JSON data in the database: unable to convert object into a string

To summarize, my data is stored in Javascript: JSONdata = { name: form.name.value, address1: form.custa.value, address2: form.custa2.value, postcode: form.custpc.value, order: fullorder, cost: document.getElementById('total&ap ...

Utilize key value pairs to retrieve data from a multi-level array

I'm looking for assistance with extracting values from an array based on key value rather than array number. $json = json_decode($stock, true); print_r($json); $sims = $json['stock'][1]['sims']; foreach ($sims as $sim) { echo ...

My GraphQL Query is throwing a JSON error when using the curlopt_postfields option. What could be causing this

I'm having some trouble with my code and I keep encountering this error message. Any ideas on what might be causing this issue? I believe I've properly escaped all the quotations. {"errors":[{"message":"json body could ...

Automating web pages with the power of Node.js

I have developed an API in PHP that accepts a 10-digit number as a variable and provides data in JSON format. For instance, the URL structure is like this: www.exampletest.com/index.php?number=8000000000. The succeeding variable will be the current number ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

Looking to fetch JSON data from a private IP that is not accessible to the public

Is there a way to retrieve JSON data from a location that is only accessible within a company's firewall? The address I am trying to access is: http://12.34.56.789:8983/app/collection/select?q=*%3A*&wt=json&indent=true My application can be ...

Is it necessary to use preg_replace on a JSON string in order to prevent null values when using json_decode?

Dealing with an outdated system that sends JSON data has caused me some trouble. I encountered a bug where using json_decode( $json_string, true); would result in returning null. After much frustration, I stumbled upon the solution here, which advised to ...

Limit access to the webpage to only one user at any given time

There are two users: X and Y, and one page called Page Z. In order to access Page Z, there is a link available. If Page Z is already open in user X's browser, I need the link to be disabled and deny access to user Y. What is the best way to achieve ...