I am trying to convert a Java object to JSON in Tomcat (currently using Jackson). Based on the fields in a RESTful request, I want to serialize only those fields. I want to support requests for any subset of the fields, so I'd like to do it at run-time (dynamically).
For example, suppose I want to support partial serialization for 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 make a request for:
GET /users/{id}/?fields=firstName,lastName
I want to get something like {"firstName":"Jack","lastName":"Johnson"}
.
If I make a request for:
GET /users/{id}/?fields=firstName
I want to get something like {"firstName":"Jack"}
.
Jackson's JSON View gives the ability to define subsets of logical properties (things accessed via getters or fields) to serialize. However, they are defined statically (using annotations) and only chosen dynamically (per serialization). In practice, I want to support requesting any subset of an object's fields, so I could potentially have thousands of JSON Views (10 fields implies 1,023 subsets!).
What JSON library supports partial serialization at run-time?