Omit null values ββin json response from Nancy FX
I am trying to create a REST service using Nancy FX in a C # environment. I can easily do a Response.AsJson and it all looks good. But I want the answer to omit any properties that are null.
I haven't been able to figure out how to do this yet.
Can anyone point me to a help document or blog post somewhere that explains how to do this.
Thanks, In JP
source to share
I would create a dynamic anonymous type and return it. So, let's say you have an object User
like this:
public class User
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
You want to pass an instance of this type as a JSON response, so you would have code like this:
Get["/user/{userid}"] = parameters =>
{
var user = UserService.GetById(Db, (string)parameters.userid);
if (user == null) return HttpStatusCode.UnprocessableEntity;
return Response.AsJson(user);
};
But you don't want to return an instance User
, instead, you want to return a separate instance of the type dynamic
, which will only implement the property if the property value is not null
for the given instance.
So, I would suggest code something like this:
Get["/user/{userid}"] = parameters =>
{
var user = UserService.GetById(Db, (string)parameters.userid);
if (user == null) return HttpStatusCode.UnprocessableEntity;
dynamic userDTO = new ExpandoObject();
userDTO.Id = user.Id;
if (!string.IsNullOrEmpty(user.FirstName)) userDTO.FirstName = user.FirstName;
if (!string.IsNullOrEmpty(user.LastName)) userDTO.Lastname = user.LastName;
return Response.AsJson((ExpandoObject)userDTO);
};
Note 1
You do not need to test Id
as this is implied by successfully returning an instance User
from the database.
Note 2
You need to use a type dynamic
so that you can include special properties. The problem is that extension methods cannot accept dynamic types. To avoid this, you need to declare it as ExpandoObject
, but use it as dynamic. This trick has a processing overhead, but it allows you to give the dynamic value ExpandoObject
when you pass it to the extension method AsJson()
.
source to share