Tutorial :How to create a JSON view from a domain object?



Question:

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?


Solution:1

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.


Solution:2

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »