Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial JSON Serialization at Run-Time (for RESTful Queries)

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?

like image 988
Action Jackson Avatar asked Aug 23 '10 17:08

Action Jackson


1 Answers

We use Google GSON to convert back and forth between Java object and JSON. I am not sure if it has the functionality you are looking for but it is very easy to use and the docs are good too.

If you can't find a library that does what you need, I second the suggestion of using looser structured classes (like HashMap) or custom representation classes for being the link between your code and the JSON. This would add another layer or two but keep the complexity down. Good luck.

like image 187
Jesse Webb Avatar answered Oct 19 '22 23:10

Jesse Webb