c# - 从 html 字符串中提取 json 对象

标签 c# .net

我遇到了一个问题,我从包含 html 的 Web 请求中获取一个字符串,但在该 html 中是一个 json 对象,我需要将其解析为一个对象以在我的代码中使用,但我陷入了困境如何做到这一点。

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

有什么想法吗?

编辑: 我还尝试将其转换为字符列表并且对它不识字,但是当它转换时,花括号消失了,并且该位置是一个空条目。

编辑2:

添加了我从请求中获取的 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>

最佳答案

  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, “ session token ”:{ “sessionToken”:“tRabFfRPwYX4fGdHZOrBYDAAoICwwCDo”, “发行者系统Id”:“380”, “创建时间”:{ “时间戳”:“2016-02-11T03:58:30-05:00” }, “到期时间”:{ “时间戳”:“2016-02-11T04:03:30-05:00” }, “最大空闲期”:0 }, “真实模式”:1, “用户名”:“我的用户名” }}

关于c# - 从 html 字符串中提取 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335948/

相关文章:

c# - .NET compact framework - 检测是否在模拟器下?

c# - Java 中 StringBuffer 的 .NET 等价物是什么?

c# - Webform 中的 HTML 助手?

c# - 如何获取成员(member)的全名

c# - C# 中的停靠面板套件不会触发 mousedown 事件

c# - IIS7的url路由问题

c# - 使用 COM 组件时出错

c# - 如何伪造/单元测试Azure存储队列?

c# - C# 是否在条件语句中使用短路评估?

c# - 使用 C# 更改 Visual Basic Power Pack 3 中 RectangleShape 的背景颜色?