请帮助我了解这里发生了什么以及它是否应该这样工作?我有一个来自 CMS 的通用对象列表:
例如List<MyCMS.Articles.Article> myArticles = articles.All
;
后来我以 JSON 格式输出列表的内容(对于 CMS UI - 表列表)。
现在一条记录将包括:
article.Title
article.Alias
article.Guid
article.Description
+
article.SeoProperties.TitleOverride
article.SeoProperties.H1Tag
article.StateProperties.IsActive
article.StateProperties.Channels
ETC...
如您所见,Article 对象具有附加的类属性 - 具有通用属性(用于 CMS 中的其他对象类型)
我还使用了一个过滤器类,它使用 LINQ 对集合执行一些过滤操作,以仅返回某个频道内的文章,例如...
所以问题是,当我将集合序列化为 JSON 时——我真正需要在我的表列表中显示的只有几个“列”,而我在其他字段中不需要——尤其是可能很长的字段,例如“描述"(从文件系统中延迟加载)等... - 我使用 DataContractJsonSerializer 进行序列化...
我需要一种方法来控制 JSON 结果中将包含哪些字段...我所做的是如果我不需要该属性并使用 [DataMember(IsRequired = false) 装饰类属性,我会使用反射将属性值设置为 null , EmitDefaultValue = false)] 属性...-它应该可以正常工作-但是-一旦我检查(甚至克隆!!)最终对象的集合以剥离字段=将值设置为“null”-属性值变为null - 应用程序范围 - 在此类对象的所有集合中......嗯?
这里有一些演示代码:
void Page_Load() {
MyCms.Content.Games games = new MyCms.Content.Games();
List<MyCms.Content.Games.Game> allGames = games.All;
MyCms.Content.Games games2 = new MyCms.Content.Games();
List<MyCms.Content.Games.Game> allGamesOther = games2.All;
Response.Write("Total games: " + allGames.Count + "<br />");
//This is our fields stripper - with result assigned to a new list
List<MyCms.Content.Games.Game> completelyUnrelatedOtherIsolated_but_notSureList = RemoveUnusedFields(allGamesOther);
List<MyCms.Content.Games.Game> gamesFiltered = allGames.Where(g=>g.GamingProperties.Software=="89070ef9-e115-4907-9996-6421e6013993").ToList();
Response.Write("Filtered games: " + gamesFiltered.Count + "<br /><br />");
}
private List<MyCms.Content.Games.Game> RemoveUnusedFields(List<MyCms.Content.Games.Game> games)
{
List<MyCms.Content.Games.Game> result = new List<MyCms.Content.Games.Game>();
if (games != null && games.Count > 0)
{
//Retrieve a list of current object properties
List<string> myContentProperties = MyCms.Utils.GetContentProperties(games[0]);
MyCms.PropertyReflector pF = new MyCms.PropertyReflector();
foreach (MyCms.Content.Games.Game contentItem in games)
{
MyCms.Content.Games.Game myNewGame = (MyCms.Content.Games.Game)contentItem.Clone();
myNewGame.Images = "wtf!"; //just to be sure we do set this stuff not only null
pF.SetValue(myNewGame, "GamingProperties.Software", ""); //set one property to null for testing
result.Add(myNewGame);
}
}
return result;
}
对象被设置为它们的“默认值”(基本上,在大多数情况下为空):
private object GetDefaultValue(Type type)
{
if (type.IsValueType)
{
try
{
return Activator.CreateInstance(type);
}
catch {
return null;
}
}
return null;
}