排除没有数据的对象

时间:2018-02-14 21:45:50

标签: c# json json.net

如何从序列化中排除对象,该对象没有在对象中序列化的字段/属性。

以下是一个简单的类作为示例。

class Item : IComponent
{
    [JsonProperty(PropertyName = "ID", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
    public int ID = 0;
}

如果我序列化一个Item对象数组,我会得到以下结果。

{
    "Items" : [
        { "$type": "Item" },
        { "$type": "Item", "ID": 1},
        { "$type": "Item", "ID": 2 }
    ]
}

我想排除数组中的第一个项目对象,因为它没有保存数据。空“默认”对象对我的用例没用。我的用例以预先填充的JObject开头,并在反序列化时覆盖数据,因此空对象实际上是无用的。

任何想法如何排除序列化时没有定义任何内容的对象?我找不到处理此问题的ObjectAttributeJsonSerializerSettings。如果需要,我可以做ContractResolver

感谢。

更新

感谢SANM2009,但该方法的问题是你必须告诉对象它是否应该是YiSerialize。但是,如果所有内容都设置为默认值或存在数据集,则需要在序列化时确定。

感谢Brian Rogers,我想我可以使用它(修改了一堆),并在我的情况下使相同的概念工作。

更新2:

Brian Rogers的例子工作得很好,但我不得不修改IsEmpty()方法,因为它没有考虑声明$ type的空JObject。

public static bool IsEmpty(JToken token)
{
        return (token.Type == JTokenType.Null) ||
                (token.Type == JTokenType.Array && !token.HasValues) ||
                (token.Type == JTokenType.Object && !token.HasValues) ||
                (token.Type == JTokenType.Object && token.Count() == 1 && token["$type"] != null);
}

谢谢大家。我希望有一些比Json.net中的设置更简单,但是很好。

1 个答案:

答案 0 :(得分:1)

序列化后对象过滤不是更好吗?

vis_by.party <- function(primal){
  require(Hmisc)
  require(effsize)

  ## Identify Primal Name for display in titles, etc.
  if(primal=="gf.60"){
    primal.name <- "Good"
  } else if(primal=="enticing.26"){
    primal.name <- "Enticing"
  } else if(primal=="safe.23"){
    primal.name <- "Safe"
  } else if(primal=="alive.11"){
    primal.name <- "Alive"
  } else {
    primal.name <- capitalize(primal)
  }

  ## Gather data for each party
  dems <- subset(vis.data, pol.dem.ec==1)
  dems <- as.vector(as.matrix(t(dems[c(which(colnames(dems)==primal))])))

  reps <- subset(vis.data, pol.rep.ec==1)
  reps <- as.vector(as.matrix(t(reps[c(which(colnames(reps)==primal))])))

  indeps <- subset(vis.data, pol.indep.ec==1)
  indeps <- as.vector(as.matrix(t(indeps[c(which(colnames(indeps)==primal))])))


  ## Calculate and Format Statistics ##

  # Kruskal-Wallis Test Across Groups
  party.data <- data.frame(y=c(dems,indeps,reps), party=c(rep("dem",length(dems)),rep("indep",length(indeps)),rep("rep",length(reps))))
  party.aov <- kruskal.test(y~party, data=party.data)
  kw.res <- paste("H = ", round(party.aov$statistic, 2), add.stars(party.aov$p.value), sep="")

  # Pairwise comparison between Dems and Indeps
  dvi.data <- data.frame(y=c(dems,indeps), party=c(rep("dem",length(dems)),rep("indep",length(indeps))))
  dvi.d <- cohen.d(y~party, data=dvi.data)
  dvi.contrast <- wilcox.test(dems, indeps)
  dvi.res <- paste("Mann-Whitney U = ", round(dvi.contrast$statistic,2), add.stars(dvi.contrast$p.value), "; Coh. D = ", round(dvi.d$estimate,2), sep="")

  # Pairwise comparison between Dems and Reps
  dvr.data <- data.frame(y=c(dems,reps), party=c(rep("dem",length(dems)),rep("rep",length(reps))))
  dvr.d <- cohen.d(y~party, data=dvr.data)
  dvr.contrast <- wilcox.test(dems, reps)
  dvr.res <- paste("Mann-Whitney U = ", round(dvr.contrast$statistic,2), add.stars(dvr.contrast$p.value), "; Coh. D = ", round(dvr.d$estimate,2), sep="")

  # Pairwise comparison between Indeps and Reps
  ivr.data <- data.frame(y=c(indeps, reps), party=c(rep("indep",length(indeps)),rep("rep",length(reps))))
  ivr.d <- cohen.d(y~party, data=ivr.data)
  ivr.contrast <- wilcox.test(indeps, reps)
  ivr.res <- paste("Mann-Whitney U = ", round(ivr.contrast$statistic,2), add.stars(ivr.contrast$p.value), "; Coh. D = ", round(ivr.d$estimate,2), sep="")


  ## Plot Results ##
  layout(matrix(c(1,0,2,4,3,4), nrow=3, ncol=2, byrow=TRUE), heights=c(1,1,1), widths=c(2,3))

  #Plot Dems
  par(mai=c(0.1,0.6,0.25,0))
  hist(dems, breaks=50, col=rgb(0,0,1,1/4), freq=FALSE, xlim=c(-3.5,3.5), xaxt="n", ylim=c(0,1), main=paste(primal.name, " among Democrats", sep=""), xlab="")
  axis(side=1, at=c(-3,-1.5,0,1.5,3))
  minor.tick(nx=8, ny=0, tick.ratio=0.5)
  lines(density(dems), col="blue", lwd=2)

  #Plot Indeps
  par(mai=c(0.1,0.6,0.8,0))
  hist(indeps, breaks=50, col=rgb(0.4,0,0.6,1/4), freq=FALSE, xlim=c(-3.5,3.5), xaxt="n", ylim=c(0,1), main=paste(primal.name, " among Independents", sep=""), xlab="")
  axis(side=1, at=c(-3,-1.5,0,1.5,3))
  minor.tick(nx=8, ny=0, tick.ratio=0.5)
  lines(density(indeps), col="purple", lwd=2)

  #Plot Reps
  par(mai=c(0.7,0.6,0.8,0))
  hist(reps, breaks=50, col=rgb(1,0,0,1/4), freq=FALSE, xlim=c(-3.5,3.5), xaxt="n", ylim=c(0,1), main=paste(primal.name, " among Republicans", sep=""), xlab="Ipsatized, Scale-Centered PI-99 Response")
  axis(side=1, at=c(-3,-1.5,0,1.5,3))
  minor.tick(nx=8, ny=0, tick.ratio=0.5)
  lines(density(reps), col="red", lwd=2)

  #Plot comparison
  plot(density(dems), col="blue", lwd=2, xlim=c(-3.5,3.5), ylim=c(0,1), main=paste("Comparison of ", primal.name, " Between Parties", sep=""), xlab="Ipsatized, Scale-Centered PI-99 Response")
  lines(density(indeps), col="purple", lwd=2)
  lines(density(reps), col="red", lwd=2)
  minor.tick(nx=4, ny=0, tick.ratio=0.5)

  #Add Legend
  legend(x=-3.5, y=1, legend=c("Democrats","Independents","Republicans"), col=c("blue","purple","red"), lwd=2, cex=1.2)

  #Add Title and Statistical Results
  mtext(primal.name, side=3, line=13.5, adj=0.5, cex=2)
  mtext("Statistical Summary", side=3, line=10.5, adj=0, font=4)
  mtext(paste("    Kruskal-Wallis Test: ", kw.res, sep=""), side=3, line=9, adj=0)
  mtext(paste("    Dems vs. Indeps: ", dvi.res, sep=""), side=3, line=7.5, adj=0)
  mtext(paste("    Dems vs. Reps: ", dvr.res, sep=""), side=3, line=6, adj=0)
  mtext(paste("    Indeps vs. Reps: ", ivr.res, sep=""), side=3, line=4.5, adj=0)


  #rm(primal,primal.name,dems,indeps,reps,party.data,party.aov,kw.res,dvi.data,dvi.d,
  #   dvi.contrast,dvi.res,dvr.data,dvr.d,dvr.contrast,dvr.res,ivr.data,ivr.d,
  #   ivr.contrast,ivr.res)
}