Halil Sahin
Halil Sahin

Reputation: 603

Wrong Serialization on LINQ Web API

I have a LINQ query as that:

public List<tblStudent> GetNames()
{
    var result = (from student in db.tblStudents.ToList()
                  select new tblStudent 
                  {
                      StudentID = student.StudentID,
                      StudentName = student.StudentName,
                      Email = student.Email,
                      IsDeleted= student.IsDeleted

                      //tblDepartment = department.tblStudents
                  });
    return result.ToList();
}

When I executed that query it gave me a result as that:

My Result

But I don't want to see null values in my result. How I can solve that problem?

Upvotes: 2

Views: 220

Answers (3)

Halil Sahin
Halil Sahin

Reputation: 603

I just added that line on my WebApiConfig.cs and my problem been solved.

 config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

Upvotes: 1

Nkosi
Nkosi

Reputation: 247393

You can use an anonymous type to return only the desired members when returning the collection from the ApiController

For example

public class MyApiController : ApiController {

    //...

    public IHttpActionResult MyControllerAction() {
        var result = myService.GetNames()
                    .Select(student => select new { //<-- Note what was done here
                          StudentID = student.StudentID,
                          StudentName = student.StudentName,
                          Email = student.Email,
                          IsDeleted= student.IsDeleted
                      });
        return Ok(result.ToList());
    }
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502406

While I haven't tried it, I'd expect you to be able to configure Json.NET to ignore null values when serializing. Within ConfigureServices, write this:

services.AddJsonFormatters(settings => settings.NullValueHandling = NullValueHandling.Ignore);

Using an anonymous type instead would work too, but that becomes trickier if you have a list where some objects have non-null values for certain properties, and other objects have null values. It's good to be aware of both approaches, so you can use whichever one is more appropriate in any situation.

Upvotes: 3

Related Questions