Java – partial JSON serialization at runtime (for restful queries)
I'm trying to convert Java objects in Tomcat to JSON (currently using Jackson) Based on the fields in the restful request, I want to serialize only these fields I want to support any subfield request, so I want to execute it at run time (dynamically)
For example, suppose I want to support partial serialization of user objects:
class User { private final String id; private final String firstName; private final String lastName; public User(String id,String firstName,String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
If I ask:
GET /users/{id}/?fields=firstName,lastName
I want something like {"firstname": "Jack", "LastName": "Johnson"}
If I ask:
GET /users/{id}/?fields=firstName
I want something like {"firstname": "Jack"}
Jackson's JSON view can define a subset of logical attributes (things accessed through accessors or fields) to serialize However, they are statically defined (using annotations) and only dynamically selected (per serialization) In fact, I want to support any subset of the request object fields, so I may have thousands of JSON views (10 fields mean 1023 subsets!)
What JSON libraries support partial serialization at run time?
Solution
We use Google gson to convert back and forth between Java objects and JSON I don't know if it has the functionality you're looking for, but it's very easy to use and well documented
If I can't find the required library, I'll take the second suggestion to use loosely structured classes (such as HashMap) or custom presentation classes as the link between code and JSON This will add another layer or two, but keep the complexity Good luck.