Cannot deserialize xml string with Newtonsoft.Json.JsonConvert.DeserializeObject

15,223

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
Share:
15,223
AMDI
Author by

AMDI

Updated on June 05, 2022

Comments

  • AMDI
    AMDI almost 2 years

    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.

  • AMDI
    AMDI over 10 years
    Thnaks for the reply.
  • AMDI
    AMDI over 10 years
    Bu the issue I am facing is I can send either a Json Object or XML.The single method needs to handle both scenarios.
  • Brian Rogers
    Brian Rogers over 10 years
    Ah. Well you never mentioned that in your question. Fortunately, that is simple enough to solve; just add a check to detect whether the string is XML. If it is, convert it to JSON. If not, parse it as usual. I've updated my answer to demonstrate.
  • AMDI
    AMDI over 10 years
    Sorry for that. i will try the solution.Thanks for the response.