Resolved Read data from API response

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
Hi All

I'm currently consuming a REST api and i need some guidance on reading the response data. My experience with reading this type of data is very minimal and i'm trying to find the best way to do it.

below is the code for getting the API data.

C#:
 public string ModitarWebRequestCall()
        {
            string apiUrl = "https://api.moditar.com/Document/GetContent";
            string username = "JohnDoe";
            string password = "Password123";
            string collection = "ea85fbf3-5858-4348-bcab-08a8f39ad30c";
            string markasread = "False";

            var request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Method = "GET";
            request.Accept = "application/xml";

            request.Headers.Add("username", username);
            request.Headers.Add("password", password);
            request.Headers.Add("collection", collection);
            request.Headers.Add("Markasread", markasread);

            string content = string.Empty;
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            content = sr.ReadToEnd();
                            sr.Close();
                            Console.WriteLine("Data received from Moditar");
                        }
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

I'm using the code below to call the above method and this is where I need to process the data.

C#:
        public void ProcessDatafromModitarApi()
        {
            var getData = new ModitarApiConnection();
            getData.ModitarWebRequestCall();
        }

What is the best way to read this data ? there are options for json, xml readers, leave it as text etc. so many choices. Any guidance on this would be greatly appreciated.
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
The more important question is what will you do with the data when you get it?

This Will be the deciding factor in what format you receive and use it.
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
And the type of data is?
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
Regardless the type received, you could store it in a class object. The good owl object oriented way...

Depending on the data types received, I can provide a better response.
 

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
Regardless the type received, you could store it in a class object. The good owl object oriented way...

Depending on the data types received, I can provide a better response.
Hi Sheepings

Sorry about that, the data is coming through as XML. From my limited knowledge on XML it looks quite complex with loads of child nodes. So i'm not quite sure how to process this and also haven't attempted anything like this in C# yet.
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
You want to Deserialize the data received into a list, and from the list to your SQL server. You can do it all from one Linq Method.

So If i understand this... you want to receive data from a request, read that data, and then insert that data to another database?

Either way, you are looking for Deserialize from XmlSerializer Class.
 

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
You want to Deserialize the data received into a list, and from the list to your SQL server. You can do it all from one Linq Method.

So If i understand this... you want to receive data from a request, read that data, and then insert that data to another database?

Either way, you are looking for Deserialize from XmlSerializer Class.

Hi Sheepings

Thank you for your advice, yes that's exactly what I need to do with the XML.
i already built the StreamReader that's receiving the data, do i have to replace all that code to use the XmlSerializer ? or can i just deserialise the content that has already come through ?
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
I'm kind of fumbling around in the dark here, and I'm not sure i'm doing this correctly but i'm getting a "root element missing" error when i hover over the exception.

C#:
            string content = string.Empty;
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            content = sr.ReadToEnd();

                            XmlSerializer serializer = new XmlSerializer(typeof(XmlElement));
                            content = (string)serializer.Deserialize(sr);

                            sr.Close();
                        }
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
And you're sure your receiving XML data in your request?

Line 10 is redundant because of line 13.

Use sr.ReadToEnd() instead of sr on line 13.

Also note that Deserialize on line 13 expects a xml reader and not a stream reader.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,604
Location
Chesapeake, VA
Programming Experience
10+
Or the OP could pass in the stream directly and bypass the stream reader.
 

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
Is the start of your XmlElement actually named XmlElement?

Show us some of your XML without any sensitive data?

Notice the usage on the docs I linked :
C#:
<?xml version="1.0"?>
<OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
   <inventory:ItemName>Widget</inventory:ItemName>
   <inventory:Description>Regular Widget</inventory:Description>
   <money:UnitPrice>2.3</money:UnitPrice>
   <inventory:Quantity>10</inventory:Quantity>
   <money:LineTotal>23</money:LineTotal>
</OrderedItem>
@Skydiver and you wonder why I prefer Json eh. 🙃
 

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
Is the start of your XmlElement actually named XmlElement?

Show us some of your XML without any sensitive data?

Notice the usage on the docs I linked :

@Skydiver and you wonder why I prefer Json eh. 🙃

Hi Sheepings, I've attached the XML file as it's quite a complex XML file, I haven't worked with anything like it before.

" Also note that Deserialize on line 13 expects a xml reader and not a stream reader. "

So do i have to re-write the stream reader code and replace it with the XMLreader code ? I was thought i could deserialize the data that had already come through the stream reader, or is that not possible ?
 

Attachments

  • response.zip
    17.4 KB · Views: 2

Sheepings

Retired Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,979
Location
UK
Programming Experience
10+
I was thought i could deserialize the data that had already come through the stream reader
Depends, which way you handle your response. The docs recommend using xml reader though, and the Deseriaize method takes a xmlreader. Note :
Or the OP could pass in the stream directly and bypass the stream reader.
If no one else does, I will try pick this up later.
 

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
I did see something on the web where the dev streamed the data into memory with MemoryStreamer and then deserialised it afterwards, not sure if i'm over complicating this for myself or not.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,604
Location
Chesapeake, VA
Programming Experience
10+
You don't even have to stream it into a memory stream (unless you are planning on deserializing the same stream more than once).

This (using the new C# 8.0 using) would be sufficient:
C#:
using var response = (HttpWebResponse)request.GetResponse();
using var stream = response.GetResponseStream();
var serializer = new XmlSerializer(typeof(OrderedItem));
return (OrderedItem)serializer.Deserialize(stream);
(If you have an older version of C#, obviously use the scoped version of using.)
 

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
You don't even have to stream it into a memory stream (unless you are planning on deserializing the same stream more than once).

This (using the new C# 8.0 using) would be sufficient:
C#:
using var response = (HttpWebResponse)request.GetResponse();
using var stream = response.GetResponseStream();
var serializer = new XmlSerializer(typeof(OrderedItem));
return (OrderedItem)serializer.Deserialize(stream);
(If you have an older version of C#, obviously use the scoped version of using.)
Thanks Skydiver

I'm just getting bogged down with all the different options and confusing myself even more. Main focus now is just to get this XML data deserialized. In your example i'm assuming that "OrderedItem" is a node in the XML file ?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,604
Location
Chesapeake, VA
Programming Experience
10+
No. It's a class where the XML data will be read into. Typically the class type name matches the XML element name but this can be overridden. You should take time to read about XML serialization and deserialization instead of just throwing code at the screen to see what sticks.

 
Top Bottom