Below is an instance of a simple job scheduler which parses xml dynamic strings to json:
XML
<Navigations>
<Navigation Name="facebook" Active ="0" ></Navigation>
</Navigations>
c#
List<NavigationData> nds = new List<NavigationData>();
foreach (object cnav in (IEnumerable)c.Navigations)
{
NavigationData nd = new NavigationData();
nd.Name = (string)((dynamic)cnav).Name;
nd.Active = XmlConvert.ToBoolean((string)((dynamic)cnav).Active); // 3
nds.Add(nd);
}
transitContent.NavigationData = JsonConvert.SerializeObject(nds);
The above program throws an exception at line 3 as:
failed to convert string to boolean with XMLConvert.ToBoolean
not able to recognize string with Convert.ToBoolean
An other type conversions possibele in this scenario? The expected result should be:
JSON
[
{
"Name": "facebook",
"Active": false
}
]
Well yes, "0" isn't a valid value for a Boolean. It sounds like you possibly want something like:
List<NavigationData> nds = new List<NavigationData>();
foreach (dynamic cnav in (IEnumerable)c.Navigations)
{
NavigationData nd = new NavigationData();
nd.Name = cnav.Name;
nd.Active = cnav.Active != "0";
nds.Add(nd);
}
transitContent.NavigationData = JsonConvert.SerializeObject(nds);
This is assuming that cnav
will expose all properties as strings (as their execution-time type).
See more on this question at Stackoverflow