views:

1513

answers:

2

I'm creating the server side implementation of an AJAX based web application, where the client side receives responses that are domain objects serialized as JSON. In order to provide a common look and feel, I would like to create templates for different types of domain objects, and re-use these as Spring views for multiple controllers.

For instance, say I have the following object graph:

A - B - C

where A and C have a many-to-many relationship. When I return an object of type A as the result of an AJAX request, I would like to return its associated data in the B and C tables. However, when I return an object of type C as the result, I would like to return just the data in table C.

Thus far the only solution I have found is to create a custom data binder in the controller; however I believe this use case is better suited as a view that can be shared among many controllers. Does a solution for this exist?

+2  A: 

Yes, you can have views that are JSON-formatted versions of your model.

Take a look at Spring-Json view and the org.springframework.web.servlet.view.json.JsonView class.

matt b
Very cool, I was actually wondering about this earlier today.
Alex Beardsley
+1  A: 

XStream has a JSON serializer and deserializer for arbitrary Java objects.

David Winslow