Cannot deserialize xml string with Newtonsoft.Json.JsonConvert.DeserializeObject
-
20-12-2019 - |
Question
Hi I am passing an xml as string
<AbcDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Abc">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>
When I am trying creating Custom Model Binder for Web Api
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
The json string passing as an parameter to the below method is an xml as string I am facing exception at Newtonsoft.Json.JsonConvert.DeserializeObject(json); Exception Details: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Solution
You are getting an error because JsonConvert.DeserializeObject()
expects JSON input, not XML. If you want to handle XML with a JObject
, you'll need to convert the XML to JSON first. The JsonConvert
class has a SerializeXmlNode()
method for this purpose.
Demo:
class Program
{
static void Main(string[] args)
{
string json = @"
<AbcDto xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Abc"">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>";
// If the json string contains XML, convert it to JSON
if (json.TrimStart().StartsWith("<"))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(json);
json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
}
// Now you can load the JSON into a JObject
var jsonObject = JObject.Parse(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
foreach (string name in jsonPropertyNames)
{
Console.WriteLine(name);
}
}
}
Output:
@xmlns:i
@xmlns
Id
Description
Name
PolicyId
Status
TimeZoneId
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow