Ran into a painful issue today when attempting to work with a sample application I was putting together. In my application I use JPA to retrieve data from an Oracle database, which I then expose via a Jersey service (running on WebLogic 12c). My front end is using Backbone.js and I was attempting to populate a backbone collection with the results of the jersey rest call.
So the REST service was written quite simply:
@Path("/productcategories") public class ProductCategoryResource { @Context ServletContext context; /* * Retrieves a list of the top level product categories and their immediate children * Implements the GET on this resource, can return values in JSON or XML */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public List getProductCategories() { ProductCategoryBll bll = new ProductCategoryBll(); return bll.listParentProductCategories( context ); } } |
Using cUrl I was able to see that what I retrieved looked like this:
{"productCategory":[{"categoryDescription":"Office Supplies","categoryId":"2","categoryLockedFlag":"N","categoryName":"Office"},{"categoryDescription":"Consumer Electronics","categoryId":"3","categoryLockedFlag":"N","categoryName":"Electronics"},{"categoryDescription":"Books, Music, and Movies","categoryId":"1","categoryLockedFlag":"N","categoryName":"Media"}]} |
This is perfectly valid shorthand JSON – it has three objects, and all are denoted to be of type productCategory. Backbone however (or maybe it is jQuery under the covers?) really did not like this – it instead was creating a collection with one thing in it – a productCategory, and then trying to parse this as my ProductCategory model object which obviously failed.
Here is my collection that was failing to parse correctly:
window.CategoryCollection = Backbone.Collection.extend({ model: ProductCategory, url: "webresources/productcategories", }); |
The fix was pretty simple once I realized what it was doing – I needed to override the collection’s parse to handle the funk it didn’t like from the Java server (alternatively I could have altered the Java end, but I really didn’t want to mess with it at the time, and it is perfectly valid JSON syntax). Here’s the altered collection:
window.CategoryCollection = Backbone.Collection.extend({ model: ProductCategory, url: "webresources/productcategories", // Override parse as the default JSON Jersey returns with a collection does not work with Backbone parse: function( resp, xhr ) { return resp.productCategory; } }); |
’til next time…
I had the same problem but found that it was easy to fix on the Java side by using the Jersey’s JSON POJO support. Some info .