Dubax
Dubax

Reputation: 3

Filter JSON response Java Spring - RESTful service

I'm trying to hide certain fields in a GET based on whether or not a user is internal.

Here is a snippet from my controller:

@RequestMapping(value = "rules", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public StandardJSON list(@ActiveUser ActiveUserId userId)
{
    StandardJSON sj = new StandardJSON();
    sj.setErrors(new ArrayList<String>());
    sj.setData(service.listAllRules());
    return sj;
}

The above returns the following JSON:

{
    "customerProfileId": "",
    "lastModifiedBy": "",
    "location": "",
    ...
}

I can determine if a user is internal or not using a getIsInternalUser() method.

How would I filter one of the json items if a user is external?

Upvotes: 0

Views: 166

Answers (2)

Garry
Garry

Reputation: 4533

If you can use Genson - Java and Scala to JSON conversion library then it can be done like this. It will exclude the "foo" field from Bar class.

Genson genson = new Genson.Builder().exclude("foo", Bar.class).create();
genson.serialize(yourObject);

Upvotes: 1

sschrass
sschrass

Reputation: 7166

A resource should be uniform. This means that a JSON referenced by an URL should yield the exact same result regardless of "who" asks for it. The only thing I am aware of are different MediaTypes.

If you need to differentiate informations for types of users make it visible by modifying the URL (e.g. add an /internal or similar wherever it fits). As a result you'll get a different URL/resource, where all kinds of private/internal informations could be served. To access this resource the auth should take place accordingly.

Upvotes: 0

Related Questions