views:

165

answers:

2

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?

A: 

I think json-lib and flex-json support more dynamic/flexible filtering.

With Jackson what some users do is to use HashMaps or JsonNodes as looser structures and do filtering from there.

Also, while this won't help you on short term, Jackson 1.6 has improvements both for JsonNode (retainAll(String... names), remove(String... names) and possibly ObjectMapper, as this is a known area for improvements.

StaxMan
btw, it is kind of funny -- at work I need exactly same support (request enumerates fields it wants) -- which is why I am also looking for more dynamic support myself.
StaxMan
+1  A: 

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.

Gweebz