Oleh Kurpiak February 2016

best practice generating object for response

i have rest server with spring. there is a lots of request where one of params is fields fields is the set of field that server should return in response. like

.../?fields=[id,name] and server should return json object with both fields i would like to know what is the best practice for generating such response. We do it like this:

private Map<String, Object> processBook(BookEntity book, Set<String> fields, String locale){
        Map<String, Object> map = new HashMap<String, Object>();
//..
        if(fields.contains(ID)){
            map.put(ID, book.getId());
        }
        if(fields.contains(ISBN)){
            map.put(ISBN, book.getIsbn());
        }
        if(fields.contains(DESCRIPTION)){
            if(locale.equals(UserLocale.UK))        map.put(DESCRIPTION, book.getDescriptionUa());
            else if(locale.equals(UserLocale.RU))   map.put(DESCRIPTION, book.getDescriptionRu());
            else                                    map.put(DESCRIPTION, book.getDescriptionEn());
        }
//..
        return map;
    }

maybe there is much better alternative

Answers


Manuel S. February 2016

Instead of having a Map, you could have and object with the attributes you need and set them, instead of adding to map.

Then you can use Google's Gson to transform your object into a Json object.

Take a look at this quick tutorial.


Peter Lawrey February 2016

One approach is to have an asMap function.

 Map<String, Object> map = book.asMap();
 map.keySet().retainAll(fields);


CroWell February 2016

Note that in your case you obtain all data from DB - fully filled BookEntity object, and then show only requested fields.

In my opinion it'd be "much better alternative" to delegate field list to appropriate downstream integration call and get BookEntity object only with necessary fields. Then mentioned above method will reduce to just one line, your DB responses will be more lightweight, so it will bring simplicity and optimization gain to your system.

Any adequate DB provides such functionality: SQL or NoSQL, etc.

P.S. Plus standard approach of Object to JSON mapping such as Jackson or GSON at top level.

Post Status

Asked in February 2016
Viewed 3,773 times
Voted 5
Answered 3 times

Search




Leave an answer