【问题标题】:How do i return related data in web api so that the json does not return the null values我如何在 web api 中返回相关数据,以便 json 不返回空值
【发布时间】:2016-08-24 15:08:39
【问题描述】:
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
}

【问题讨论】:

  • 像这样返回 json { "Id": 2, "Name": "Meilkles", "Address": "samora machel avenue", "Description": "luxury hotel", "Offering": “游泳”,“Gps”:“3672.22”,“NumberOfRooms”:5444,“佣金”:65,“HotelTypeName”:“Lodge”,“评级”:3,“LocationId”:1,“图片”:“~ /Banners/download(7).jpg", "Comments": null, "Favorites": null, "Location": null, "HotelType": null, "Locations": null },
  • 我编辑了您的问题以添加结果,这应该是编辑,而不是评论。如果您有更多信息,请编辑它。

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


【解决方案1】:

为什么不创建一个没有为空的 HotelsDetailsDto 属性的 Hotel 类,然后让 HotelsDetailsDto 类从 Hotel 继承。而是返回一个列表。

这会起作用,除非 HotelsDetailsDto 是通过 linq to SQL 动态生成的。在这种情况下,提供 Hotel 和 HotelsDetailsDto 之间的映射以生成列表

【讨论】:

    【解决方案2】:

    将此代码放入WebApiConfig:

    此代码在应用程序级别返回 json 时删除所有 null 属性

    config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
    

    如果您想从特定模型中删除 null 属性,请使用以下代码:

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Comments{ get; set; }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多