JSON.Net ignoring class with only null properties

╄→尐↘猪︶ㄣ 提交于 2019-12-11 02:49:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!