我遇到了一个问题,我从一个包含html的web请求中得到一个字符串,但是在html内部是一个json对象,我需要解析一个对象以便在我的代码中使用但我仍然坚持如何做这个。
我尝试使用IndexOf()和LastIndexOf()但是当我尝试将它们指向第一个和最后一个花括号时,我得到一个-1的索引和一个异常。
有任何想法吗?
编辑:我也尝试将它转换为一个字符列表并对其进行不计算,但是当它被转换时,花括号消失了,位置是一个空条目。
Aaditi:
添加了我从请求获得的html,其中我需要提取的第3-5行。
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body onload="parent.postMessage('redirectResponse=
{"messageId":"4232450191","errorCode":0,"sessionToken":
{"sessionToken":"tRabFfRPwYX4fGdHZOrBYDAAoICwwCDo","issuerSystemId":"380","creationTime":
{"timestamp":"2016-02-11T08:58:30.000+00:00"},"expirationTime":
{"timestamp":"2016-02-11T09:03:30.000+00:00"},"maxIdlePeriod":0},
"realMode":1,"username":"myUserName"}
', 'https://target.site.com');"></body></html>
你能提供你收到的html字符串吗?
更新:
可能是编码的问题....
尝试:
Encoding trouble with HttpWebResponse
要么
Is it possible to get data from web response in a right encoding
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
如果你在上面的链接中找不到解决方案,那么发布你正在使用的代码......
string htmlText = Resources.html;
string jsonPtn = @"\{(?:[^\{\}]|(?<o>\{)|(?<-o>\}))+(?(o)(?!))\}";
string input = htmlText.Substring(htmlText.IndexOf("redirectResponse="));
Match match = Regex.Matches(input, jsonPtn, RegexOptions.Multiline | RegexOptions.IgnoreCase)[0];
string jsonText = match.Groups[0].Value;
var jsonObj = JObject.Parse(jsonText);
jsonObj将如下:
{{“messageId”:“4232450191”,“errorCode”:0,“sessionToken”:{“sessionToken”:“tRabFfRPwYX4fGdHZOrBYDAAoICwwCDo”,“issuerSystemId”:“380”,“creationTime”:{“timestamp”:“2016-02 -11T03:58:30-05:00“},”expirationTime“:{”timestamp“:”2016-02-11T04:03:30-05:00“},”maxIdlePeriod“:0},”realMode“: 1,“用户名”:“myUserName”}}