Json.Net: How to stop empty elements to be converted as somenode:null while converting XML to JSON



I am using Newton Json.net library to convert XML to JSON. My XML sample is



<space>
<frame>
<photo img="cakecollage1.jpg" />
<text string="Browse my cake space" />
<rule type="F" img="cakecollage9.jpg" x="150" y="0" w="300" h="250" />
<rule />
</frame>
<frame>
<photo img="cakecollage2.jpg" />
<rule/>
<rule/>
</frame>
</space>


Following code is written to convert it to Json.



XmlDocument doc = new XmlDocument();
doc.Load("Doc.xml");

string json = JsonConvert.SerializeObject(doc, new Newtonsoft.Json.JsonSerializerSettings() {NullValueHandling = NullValueHandling.Include, MissingMemberHandling = MissingMemberHandling.Ignore });


And the OUTPUT is :



{
"space": {
"frame": [
{
"photo": {
"@img": "cakecollage1.jpg"
},
"text": {
"@string": "Browse my cake space"
},
"rule": [
{
"@type": "F",
"@img": "cakecollage9.jpg",
"@x": "150",
"@y": "0",
"@w": "300",
"@h": "250"
},
null
]
},
{
"photo": {
"@img": "cakecollage2.jpg"
},
"rule": [
null,
null
]
}
]
}
}


My requirement is that the OUTPUT should not contain any null values. I mean I don't want



"rule": [
null,
null
]


at all in my object. Wherever empty node is there in XML, that element should not be converted.


Thanks in advance, Satya


No comments:

Post a Comment