XML to JSON Conversion Issue

Robin 66 Reputation points
2021-09-23T08:41:43.117+00:00

Hi,

I am trying to pull some data from the web using HttpWebRequest. I don't know how to access some variables as they are starting with a @ sign and returning 0 or null values.

This is the code I am using to pull the data.

            var httpRequest = (HttpWebRequest)WebRequest.Create(faUrl);  
            httpRequest.Headers["Authorization"] = ConfigurationData.cfgToken;  

            try  
            {  
                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();  
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))  
                {  
                    result = streamReader.ReadToEnd();  
                    streamReader.Close();  
                }  
            }  

This is what I am getting in the results variable in debug using the XML Visualizer.

134563-messageheaders.jpg

This is the code I am using to deserialize.

            XmlDocument xmlDoc = new XmlDocument();  
            xmlDoc.LoadXml(result);  
            var fromXml = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.Indented);  
            var jsonText = JsonConvert.DeserializeObject<RootObjects.Rootobject>(fromXml);  

This is what I see in fromXML variable using the Text Visualizer.

134641-textvisualizer.jpg

Now if you see the values for _count, _startindex and _totalcount they are 0 and _xmlns is null. But if you see the previous images, they have values.

134500-jsontext.jpg

How can I get the values into my variables? I can successfully get the reference and status variables as they don't start with @.

This is the RootObject class.

class RootObjects  
{  

    public class Rootobject  
    {  
        public Messageheaders messageheaders { get; set; }  
    }  

    public class Messageheaders  
    {  
        public Messageheader[] messageheader { get; set; }  
        public string _xmlns { get; set; }  
        public int _startindex { get; set; }  
        public int _count { get; set; }  
        public int _totalcount { get; set; }  
    }  

Appreciate any help. (I am not an expert C# programmer).

Thanks,

Robin

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,616 questions
0 comments No comments
{count} vote

Accepted answer
  1. Karen Payne MVP 35,386 Reputation points
    2021-09-23T09:06:15.1+00:00

    When a property starts with @ you need to alias it.

    For Json.net

    [JsonProperty("@someVar")]
    public int AliasNameGoesHere { get; set; }
    

    For System.Text.Json

    [JsonPropertyName("@someVar")]
    public int AliasNameGoesHere { get; set; }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful