11551

Jersey serializes character value to ASCII equivalent numeric string

Question:

I am implementing simple RESTful webservice using Jersey API. My server project is hosted on Apache Tomcat ver 6.0 and it contains <strong>asm-3.0.jar</strong>, <strong>jersey-bundle-1.9.1.jar</strong> and <strong>jsr311-api-1.1.1.jar</strong>.

I have two resource classes. One is UserItemsResource which is intended to represent collection of UserItem objects. The other one is UserItemResource which represents a single UserItem resource.

Below is code for UserItemsResource class:

@Path("/useritems") public class UserItemsResource { @Context UriInfo uriInfo; @Context Request request; @Path("{userId}") public UserItemResource getUserItemResource(@PathParam("userId") long userId) { return new UserItemResource(uriInfo, request, userId); } }

The UserItemResource class:

public class UserItemResource { @Context UriInfo uriInfo; @Context Request request; private long userId; public UserItemResource(UriInfo uriInfo, Request request, long userId) { this.uriInfo = uriInfo; this.request = request; this.userId = userId; } @GET @Produces(MediaType.APPLICATION_JSON) public UserItem getUserItem() { return new UserItem(userId, 'M', "Pawan"); } }

And the UserItem class:

@XmlRootElement public class UserItem { private long userId; private char sex; private String displayName; public UserItem() { } public UserItem(long userId, char sex, String displayName) { this.userId = userId; this.sex = sex; this.displayName = displayName; } public long getUserId() { return userId; } public char getSex() { return sex; } public String getDisplayName() { return displayName; } public void setUserId(long userId) { this.userId = userId; } public void setSex(char sex) { this.sex = sex; } public void setDisplayName(String displayName) { this.displayName = displayName; } }

When I invoke the resource (like /useritems/101), I am getting following response from server.

HTTP/1.1 200 OK Date: Wed, 24 Oct 2012 11:30:35 GMT Transfer-Encoding: chunked Content-Type: application/json Server: Apache-Coyote/1.1 { "displayName": "Pawan", "sex": "77", "userId": "101" }

You can see that the value for <strong>"sex"</strong> attribute is generated as <strong>"77"</strong>, which is ASCII equivalent of character 'M'. I believe this should come as "M" only, so that my client code can successfully parse it back to 'M'. I am using <strong>Jackson</strong> API (ver 2.0.2) to parse the json entity in the server response back to object of UserItem class.

Am I missing something? Or is this a bug?

Answer1:

Jersey supports few JSON notations and each one of them has a slightly different convention on how the resulting JSON should look like. You can see the difference between notations in this <a href="http://jersey.java.net/nonav/apidocs/1.9.1/jersey/com/sun/jersey/api/json/JSONConfiguration.Notation.html" rel="nofollow">JavaDoc</a>. The default one is MAPPED which put quotes around numbers in JSON output as you've already found out.

There are two things you can do:

<ul><li>turn on the <a href="http://jersey.java.net/nonav/documentation/latest/json.html#json.pojo.approach.section" rel="nofollow">Jackson POJO support</a> which uses the Jackson library to create JSON output (maybe this would be a better option if you're using Jackson on the client side as well). There is also an example how to use it - <a href="https://github.com/jersey/jersey-1.x/tree/master/jersey/samples/jacksonjsonprovider" rel="nofollow">JacksonJsonProvider</a>.</li> <li>use NATURAL JSON notation which handles numbers as you'd expect. To do this you need to provide a custom <a href="http://jsr311.java.net/nonav/javadoc/javax/ws/rs/ext/ContextResolver.html" rel="nofollow">ContextResolver</a> and register it in your application. Examples how to achieve this can be found in <a href="http://jersey.java.net/nonav/documentation/latest/" rel="nofollow">Jersey User Guide</a> (<a href="http://jersey.java.net/nonav/documentation/latest/json.html#d4e928" rel="nofollow">JSON Support - Configuration Options</a>) or in one of the samples <a href="https://github.com/jersey/jersey-1.x/tree/master/jersey/samples/json-from-jaxb" rel="nofollow">json-from-jaxb</a> (see <a href="https://github.com/jersey/jersey-1.x/blob/master/jersey/samples/json-from-jaxb/src/main/java/com/sun/jersey/samples/jsonfromjaxb/config/JAXBContextResolver.java" rel="nofollow">JAXBContextResolver</a>).</li> </ul>

Recommend

  • Facebook SDK - Nothing happens after login
  • MinMax Heap implementation without an array
  • google map and api shows different results
  • JSON data - Group by days of the week(Sun,Mon,Tue, Wed,Thu,Fri,Sat) using Javascript/Jquery
  • Distribute numbers to two “containers” and minimize their difference of sum
  • how to limit a click event applied to the from executing on a jquery datatable in the body
  • web2py: How to execute instructions before delete using SQLFORM.smartgrid
  • Is it possible to add a hyperlink to a UIAlertController?
  • How can I find the difference between two times [duplicate]
  • XtraGrid - Export To Excel
  • Google Geocoding API limit exceeded on cell network, but not on wifi
  • Raphael-GWT: fill image of a shape (Rect) appears offset. How to resolve this?
  • How do I link when building with llvm libraries?
  • Validating a Firebase Key [duplicate]
  • Jekyll - How do I create pages in the root directory?
  • Map Annotation Disclosure Indicator - Xamarin.Form
  • On unchecking a checkbox trigger an event
  • Spring annotation @Order
  • Custom Timeline items in Glimpse
  • android : speech recognition what are the technologies available
  • Optimization of optim() in R ( L-BFGS-B needs finite values of 'fn')
  • how to add dashed border on highcharts “area” graph for every point
  • Javascript inside HTML import not affecting imported HTML
  • C# code can't “see” the methods in my C++ dll
  • Java Collections.shuffle() weird behaviour [closed]
  • How to make Rss News Reader application in android …? [closed]
  • Copy and paste data from multiple workbooks to a worksheet in another Workbook
  • Create an average of multiple excel chart without the data source
  • Print Longitude and Latitude in textbox Android
  • iphone image to video issue in video speed
  • read part of h5 dataset python
  • VLOOKUP in IMPORTRANGE
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • How do I use TagLib-Sharp to write custom (PRIV) ID3 frames?
  • Write to .csv file with PHP (Commas in Data Error)
  • CAS 4 - Not able to retrieve the LDAP groups after successful authentication
  • JavaScript RegExp Replace
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}