简体   繁体   中英

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?

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);

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM