2015-04-23 34 views
-1

您好我有C#.NET這下面的代碼解析HTML代碼來獲得一個JSON地產出

ASCIIEncoding encoding = new ASCIIEncoding(); 
string postData = "membershipcardnumber=" + Cardnumber; 
postData += ("&terminalname=" + TerminalName); 
postData += ("&serviceid=" + CasinoID); 
byte[] data = encoding.GetBytes(postData); 

HttpWebRequest myRequest = 
    (HttpWebRequest)WebRequest.Create("http://myurl"); 
myRequest.Method = "POST"; 
myRequest.ContentType = "application/x-www-form-urlencoded"; 
myRequest.ContentLength = data.Length; 
Stream newStream = myRequest.GetRequestStream(); 

newStream.Write(data, 0, data.Length); 
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse(); 
// Get the stream associated with the response. 
Stream receiveStream = response.GetResponseStream(); 
// Pipes the stream to a higher level stream reader with the required encoding format. 
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); 
Console.WriteLine("Response stream received."); 
var egm_response = readStream.ReadToEnd(); 
Console.WriteLine(egm_response); 

變量egm_response輸出完整的HTML代碼。這只是其中的一部分:

<div class="result" style="margin-left: 20px;"> 
     <p>JSON Result :</p> 
    {"CreateEgmSession":{"IsStarted":0,"DateCreated":"","TransactionMessage":"Terminal already has an active session.","ErrorCode":37}} </div> 
<div class="clear"></div> 

我怎樣才能得到或解析這個網站只有ErrorCode之後獲得的價值?

回答

1

首先,服務應返回JSON,而不是HTML和JSON的組合。如果它是JSON,則可以使用JSON.NET將JSON響應解析爲.NET對象,您可以要求該屬性爲ErrorCode屬性。

其次,你可以使用regex匹配ErrorCode

"ErrorCode"\:\s+(\d+) 

我會建議如果可能的話去選擇1,因爲這將讓您的生活輕鬆了許多。