Reputation: 103
I have an XML from a stored procedure in SQL Server, this XML is converted into JSON and then returned from a Web API method.
This is how I'm converting XML to JSON
XmlDocument doc = new XmlDocument();
doc.LoadXml(reportXmlString);
string jString = JsonConvert.SerializeXmlNode(doc);
JObject jObject = JObject.Parse(jString);
return jObject;
I want to get numeric values in JSON as numbers... without quotes
What I have now
{
"Report": {
"ReportItem": [
{
"Name": "MyObjectName",
"Revenue": "99999.45"
}
]
}
}
What I want to have
{
"Report": {
"ReportItem": [
{
"Name": "MyObjectName",
"Revenue": 99999.45
}
]
}
}
I don't have any classes for this XML, I don't map it anywhere, I'm just receiving XML from stored procedure, converting it to JSON and returning it to user.
Here is XML which I'm parsing to JSON
<Report xmlns:json="http://james.newtonking.com/projects/json">
<ReportItem>
<Name>MyObjectName</Name>
<Revenue>99999.45</Revenue>
</ReportItem>
</Report>
Is there any way to do this without creating a classes with types for each field?
Thanks.
Upvotes: 1
Views: 859
Reputation: 4250
A bit messy but you could write your own JsonConverter (this won't fix booleans as written if they're also coming out as strings):
class NumberConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (Double.TryParse(value.ToString(), out var d))
{
writer.WriteValue(d);
}
else
{
writer.WriteValue(value.ToString());
}
}
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
and then use it like this:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
string jString = JsonConvert.SerializeXmlNode(doc);
JObject jObject = JObject.Parse(jString);
var fixedString = JsonConvert.SerializeObject(jObject, new NumberConverter());
var fixedObject = JObject.Parse(fixedString);
return fixedObject;
Upvotes: 2