问题
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; }
}
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.
Is this possible?
回答1:
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.
来源:https://stackoverflow.com/questions/8028069/json-net-ignoring-class-with-only-null-properties