JSON.Net忽略类,只有空的属性,属性、JSON、Net

2023-09-06 05:28:55 作者:扇你、一巴掌

继在我的最后一个问题(http://stackoverflow.com/questions/8027748/render-c-sharp-class-as-javascript/8027824#8027824),我现在使用JSON.net将一些班JSON。伟大的作品,但我有一些类,它包含其他类的成员。例如:

Following up on my last question (http://stackoverflow.com/questions/8027748/render-c-sharp-class-as-javascript/8027824#8027824), I'm now using JSON.net to convert some classes to JSON. Works great, but I have some class which contain other classes as members. For instance:

public class Parent
{
   public Child Child { get; set; }
   public string Var { get; set; }
}

当我使这个使用json.net,我可以设置串行忽略空值。这意味着,当它并没有被设置无功部件不打印。我想以此为基础的价值观相同的行为对儿童成员。因此,当孩子的所有成员都为空,全班呈现为{},它应在父对象产品总数被忽略。

When I render this using json.net, I can set the serializer to ignore nulls. This means the Var member isn't printed when it hasn't been set. I'd like the same behaviour for the Child member, based upon it's values. So when all members of Child are null, the entire class renders as "{}" and it should be ignored in the parent object alltogether.

这可能吗?

推荐答案

我没有用JSON.Net为我自己,所以我不知道这是做的方式。

I haven't used JSON.Net for myself, so I don't know if this is the way to do it.

不过,我可能会建议是:你可以使用反射来找出是否所有的字段都为空(或者有不太多,只是手动测试)。如果是这样,产生 {} ,如果不是,授人以任何转换器将被使用,否则。

But what I might suggest is if you're able to plug in your own JsonConverter for Child instances: you could use reflection to find out if all fields are null (or if there aren't too many, just test manually). If so, produce {}, if not, delegate to whatever converter would have been used otherwise.