EliteZalba
EliteZalba

Reputation: 55

How to get returned object from WebResponse

I'm trying to use a web service to return an array to my GUI, but I don't know how to actually pull the array from the WebResponse.

This is a method in the GUI to make the call to the web service:

public static ArrayList getList()
{
    String[] list;

    WebRequest request = WebRequest.Create("localhost:8080/test");
    WebResponse response = request.GetResponse();
    list = ??? //<--What do I put here to actually access the returned array?

    return response;
}

Upvotes: 2

Views: 6880

Answers (1)

SefTarbell
SefTarbell

Reputation: 342

The answer to this would depend a lot on the format of the response. Is it JSON? XML?

If we assume that it is a JSON response representing a list of strings, you could do something like this:

using (var response = request.GetResponse() as HttpWebResponse)
{
    Stream responseStream = response.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        // get the response as text
        string responseText = reader.ReadToEnd();

        // convert from text 
        List<string> results = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(responseText);

        // do something with it
    }
}

(this does require JSON.net)

Upvotes: 5

Related Questions