2015-06-03 91 views
0

我想要使用Web服務將數組返回到我的GUI,但我不知道如何從WebResponse實際拉數組。如何從WebResponse返回對象

這是GUI的方法,使調用Web服務:

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; 
} 

回答

1

這個問題的答案將取決於很多的響應的格式。它是JSON嗎? XML?

如果我們認爲它是代表一個字符串列表的JSON響應,你可以做這樣的事情:

using (var response = request.GetResponse() as HttWebResponse) 
{ 
    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 = JsonConvert.DeserializeObject<List<string>>(responseText); 

     // do something with it 
    } 
} 

(這確實需要JSON.net)