【问题标题】:Extract a json object from html string从 html 字符串中提取一个 json 对象
【发布时间】:2016-02-11 09:56:21
【问题描述】:

我遇到了一个问题,即我从包含 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>

【问题讨论】:

  • 如果您不帮助我们了解您在做什么,我们将如何帮助您?你在使用什么库?您的代码的相关部分是什么样的?
  • 我正在使用 c# .net 并试图从我从服务器获得的 Web 请求中提取 json 对象。我正在使用我的程序开发该网站的登录功能。

标签: c# .net


【解决方案1】:
  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", “错误代码”:0, “会话令牌”:{ "sessionToken": "tRabFfRPwYX4fGdHZOrBYDAAoICwwCDo", "issuerSystemId": "380", “创作时间”:{ “时间戳”:“2016-02-11T03:58:30-05:00” }, “到期时间”:{ “时间戳”:“2016-02-11T04:03:30-05:00” }, “最大空闲时间”:0 }, “真实模式”:1, “用户名”:“我的用户名” }}

【讨论】:

  • 太棒了!这对我帮助很大!
【解决方案2】:

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

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

【讨论】:

  • 添加了我在邮件中得到的回复。
【解决方案3】:

公共类 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);
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多