user3720455
user3720455

Reputation: 93

Does a pattern exist for serializing Java objects to JSON?

This question is not concerning the exact specifics of how to serialize a Java object to a JSON representation, but rather a scalable and testable pattern for serializing Java objects to JSON. The system in which I'm maintaining has the notion of varying levels of granularity with regards to serialization of objects. For example, the system has a concept of a Project. A Project has the following fields:

When serializing a list of Projects, it's useful to only return the "summary" information:

Omitting the more detailed stuff. However, when request a single Project, a "detailed" view is returned which includes everything. Most objects in the system have this notion of a summary and a detail view, but I'm finding that in most cases, I'm either returning too much or too little information.

To handle which attributes are returned for which view, I've simply annotated the class, and described a summary and a detail view:

@Json(summary = { "name", "description", "owner" },
      detail = { "name", "description", "owner", "tasks", "changes", ... }
class Project {
    private String name;
    ...
}

This works decently, but as I mentioned above, I find in most cases, I'm either returning too much or too little. I would be interested to see what kind of patterns exist out there for a flexible approach to getting the data I need. Am I doing it wrong if I'm finding that I'm needing to return different representations of my data? Should I pick a set number of object representations and stick with that? Thanks for your help.

Upvotes: 2

Views: 387

Answers (1)

Spectre
Spectre

Reputation: 658

You could use subclassing with an automatic serialisation framework. For example using JAXB (which supports both JSON and XML):

class DetailSummary {
    public @XmlElement String name;
    public @XmlElement String description;
    public @XmlElement String owner;
}

class Detail extends DetailSummary {
    public @XmlElement List<Task> tasks;
    ...
}

This approach allows multiple levels of detail but forces you to use your classes as simple records.

Upvotes: 1

Related Questions