繁体   English   中英

从html字符串中提取一个json对象

[英]Extract a json object from html string

我陷入了一个问题,即我从包含html的Web请求中获取一个字符串,但是在html中是一个json对象,我需要将其解析为要在我的代码中使用的对象,但我仍然坚持如何做这个。

我尝试使用IndexOf()和LastIndexOf(),但是当我尝试将它们指向第一个和最后一个花括号时,我得到的索引为-1和一个异常。

有任何想法吗?

编辑:我也曾尝试将其转换为字符列表,并对此表示怀疑,但是当转换时,花括号消失了,位置是一个空条目。

EDIT2:

添加了我从请求中获取的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字符串吗?

更新:

可能是编码问题。

尝试:

HttpWebResponse的编码问题

要么

是否可以通过正确的编码从Web响应中获取数据

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

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

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

公共类MyHtmlTagRemover {

public static void main(String a[]){
    String text = "<B>I don't want this to be bold<\\B>";
    System.out.println(text);
    text = text.replaceAll("\\<.*?\\>", "");
    System.out.println(text);
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM