如何在web api中返回相关数据,以便json不返回空值

时间:2016-07-15 07:46:50

标签: c# json entity-framework asp.net-web-api

namespace POS_Backend_.Controllers
{
    public class hotelapiController : ApiController
    {
        private POSDBEntities db = new POSDBEntities();

        // GET: api/hotelapi
        public IList<HotelsDetailsDto> GetHotels()
        {
            return db.Hotels.Select(p => new HotelsDetailsDto 
            {   Id = p.Id,
                Name = p.Name,
                Address = p.Address,
                Description = p.Description,
                Offering = p.Offering,
                Gps = p.Gps,
                NumberOfRooms = p.NumberOfRooms,
                Commission = p.Commission,
                Rating = p.Rating,    
                HotelTypeName=p.HotelTypeName,
                Image = p.Image,
                LocationId = p.LocationId,
            }).ToList();
        }

我得到以下结果:

{
    "Id": 2,
    "Name": "Meilkles",
    "Address": "samora machel avenue",
    "Description": "luxury hotel",
    "Offering": "swimming",
    "Gps": "3672.22",
    "NumberOfRooms": 5444,
    "Commission": 65,
    "HotelTypeName": "Lodge",
    "Rating": 3,
    "LocationId": 1,
    "Image": "~/Banners/download(7).jpg",
    "Comments": null,
    "Favourites": null,
    "Location": null,
    "HotelType": null,
    "Locations": null
}

2 个答案:

答案 0 :(得分:0)

为什么不创建一个没有HotelsDetailsDto属性为null的类酒店,然后让类HotelsDetailsD从酒店继承。改为返回一个列表。

除非通过linq到SQL动态生成HotelsDetailsDto,否则这将有效。在这种情况下,请提供Hotel和HotelsDetailsDto之间的映射以生成List

答案 1 :(得分:0)

将此代码放入WebApiConfig:

此代码在应用程序级别返回json时删除所有ng-pattern="/[A-Z]{5}\d{4}[A-Z]{1}/i"属性

null

如果要从特定模型中删除config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; 属性,请使用以下代码:

null

希望得到这个帮助。