[英]How do i return related data in web api so that the json does not return the null values
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
}
為什么不創建一個沒有空的HotelsDetailsDto屬性的Hotel類,然后讓HotelsDetailsDto類從Hotel繼承。 而是返回一個列表。
除非通過linq to SQL動態生成HotelsDetailsDto,否則這將起作用。 在這種情況下,提供Hotel和HotelsDetailsD之間的映射以生成列表
將此代碼放在WebApiConfig中:
當json在應用程序級別返回時,此代碼刪除所有null
屬性
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
如果要從特定模型中刪除null
屬性,請使用以下代碼:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Comments{ get; set; }
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.