【问题标题】:Parse HTML Code to get a JSON property out [duplicate]解析 HTML 代码以获取 JSON 属性 [重复]
【发布时间】:2015-04-23 06:31:36
【问题描述】:

您好,我有以下 C#.Net 代码

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>

如何获取或解析此 html 并仅获取 ErrorCode 之后的值?

【问题讨论】:

    标签: c# html json parsing httpresponse


    【解决方案1】:

    首先,服务应该返回 JSON,而不是 HTML 和 JSON 的组合。如果是 JSON,您可以使用 JSON.NET 将 JSON 响应解析为 .NET 对象,您可以要求 ErrorCode 属性。

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

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

    如果可能,我建议您选择选项 1,因为这会让您的生活更轻松。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多