Peter Bratton
Peter Bratton

Reputation: 6408

How to create a JSON view from a domain object?

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?

Upvotes: 3

Views: 4604

Answers (2)

David Winslow
David Winslow

Reputation: 8590

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

Upvotes: 1

matt b
matt b

Reputation: 140041

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.

Upvotes: 2

Related Questions