2

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 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.