HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

.NET REST API JSON Filtering

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
restnetjsonapifiltering

Problem

My question, REST API and lazy loading objects, didn't receive any answers (or many views), so here is my attempt at the solution.

Problem overview:

My mobile app requests a list of objects through a HTTP REST API but only required a small subset of each item to display items in a list. Other larger properties should not be returned unless requested i.e. in an an object detailed view.

My attempt:

API will act as normal unless a querystring is appended with the fields that are required.

I know that I need to fix the requiredFields.Contains(property.Name) call to ignore case during comparison.

My other concern is that this code is redundant due to my use of Automapper that may include functionality similar to this.

Also, could it be more efficient?

public static Object FilterFields(Object target, Uri requestUri)
    {
        NameValueCollection mapQuery = UriExtensions.ParseQueryString(requestUri);

        IEnumerable requiredFields = null;

        if (mapQuery != null && mapQuery.Get("fields") != null)
            requiredFields = mapQuery.Get("fields").Split(new char[] { ',' });

        if (requiredFields != null)
        {
            foreach (PropertyInfo property in target.GetType().GetProperties())
            {
                if (!requiredFields.Contains(property.Name))
                {
                    property.SetValue(target, null);
                }
            }
        }

        return target;
    }

Solution

Style

Be consistent in your style. If you use braces {} for single if statements then you should use them always.

Using guard conditions help you to save horizontal space.

NameValueCollection mapQuery = UriExtensions.ParseQueryString(requestUri);
if (mapQuery == null) { return target; }

string fields = mapQuery.Get("fields");
if (String.IsNullOrEmpty(fields)) { return target; }

IEnumerable requiredFields = fields.Split(new char[] { ',' });
if (requiredFields == null) { return target; }  

your loop here


otherwise your code looks good.

Code Snippets

NameValueCollection mapQuery = UriExtensions.ParseQueryString(requestUri);
if (mapQuery == null) { return target; }

string fields = mapQuery.Get("fields");
if (String.IsNullOrEmpty(fields)) { return target; }

IEnumerable<string> requiredFields = fields.Split(new char[] { ',' });
if (requiredFields == null) { return target; }  

your loop here

Context

StackExchange Code Review Q#69602, answer score: 5

Revisions (0)

No revisions yet.