从html字符串中提取json对象

问题描述 投票:1回答:2

我遇到了一个问题,我从一个包含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>
c# .net
2个回答
0
投票

你能提供你收到的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));
                }

如果你在上面的链接中找不到解决方案,那么发布你正在使用的代码......


0
投票
  1. 您可以使用正则表达式来剪切Json文本。
  2. 使用Newtonsoft.Json包解析Json文本。
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”}}

© www.soinside.com 2019 - 2024. All rights reserved.