当从DB返回Json结果时隐藏DB属性



我如何隐藏隐藏/替换属性返回json从db?

在我的例子中,如果Download_Link属性为空,我不想在json 中显示它
var x = db.Books.OrderByDescending(p=>p.Book_id).Take(200).ToList();   

return Json(x.Select(p => new
{
Title = p.Book_name,
ISBN = p.ISBN,
Edition = p.EditionValue,
Pages = p.PageCount,
Authors = p.Author_name,
Download_Link = p.Pdf_Path_Local.Replace("~","https://s1.bookz.cc")

}
), JsonRequestBehavior.AllowGet);

我认为唯一的方法就是创建两个类

public class JsonWithoutLink
{
public string Title { get; set; }
public string ISBN { get; set; }
public string Edition { get; set; }
public int Pages { get; set; }
public string Authors { get; set; }
}
public class JsonWithLink : JsonWithoutLink
{
public string Download_Link { get; set; }
}
public class Book
{
public int Book_id { get; set; }
public string Book_name { get; set; }
public string ISBN { get; set; }
public string EditionValue { get; set; }
public int PageCount { get; set; }
public string Author_name { get; set; }
public string Pdf_Path_Local { get; set; }
}

注意我假设Book类

接下来你需要声明一个委托来管理条件逻辑

Func<Book, JsonWithoutLink> ConditionalSelection = delegate (Book b)
{
if (string.IsNullOrEmpty(b.Pdf_Path_Local))
{
return new JsonWithoutLink
{
Authors = b.Author_name,
Edition = b.EditionValue,
ISBN = b.ISBN,
Pages = b.PageCount,
Title = b.Book_name
};
}
else
{
return new JsonWithLink
{
Authors = b.Author_name,
Edition = b.EditionValue,
ISBN = b.ISBN,
Pages = b.PageCount,
Title = b.Book_name,
Download_Link = b.Pdf_Path_Local.Replace("~", "https://s1.bookz.cc")
};
}
};

那么在select语句中,您需要执行以下操作(在本例中,我使用List来模拟上下文)

public IEnumerable<JsonWithoutLink> get()
{
var list = new List<Book>
{
new Book
{
Author_name = "Max",
Book_id = 1,
Book_name = "Book 1",
EditionValue = "asdf",
ISBN = "1234",
PageCount = 3,
Pdf_Path_Local = "~/somePath"
},
new Book
{
Author_name = "Max",
Book_id = 1,
Book_name = "Book 1",
EditionValue = "asdf",
ISBN = "1234",
PageCount = 3
}
};
return getJsons(list.AsQueryable().OrderByDescending(b => b.Book_id));
}
public  IEnumerable<JsonWithoutLink> getJsons(IOrderedQueryable<Book> books)
{
var list =  books
.Select(ConditionalSelection).ToList();
return list;
}

最后的调试确保一切正确proff

最新更新