【问题标题】:Convert html to json in c#在c#中将html转换为json
【发布时间】:2017-10-01 01:04:15
【问题描述】:

我有一个 c# 帖子返回我的 html。我的帖子正在检查组织名称并返回具有该名称的组织列表。我的问题是帖子返回整个页面的 html,我只想要组织列表。我觉得应该转成json,还是有其他可能?

发布方式:

WebRequest request = WebRequest.Create("http://www.mfinante.ro/numeCod.html");
// Set the Method property of the request to POST.
request.Method = "POST";

// Create POST data and convert it to a byte array.
string postData = "judet=40&name=ORACLE&submit=Vizualizare";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;

// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();

// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.

Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

【问题讨论】:

  • 1.从 html 中提取必要的信息 2. 构造对象 3. 转换为 json
  • @LeiYang 你能帮我做这些东西吗?

标签: c# html json post


【解决方案1】:

根据端点,您可能会很幸运地在请求中添加 Accept 标头,要求提供 JSON。

我不知道可能会在 WebRequest 上设置什么属性,但它可能类似于

request.Accept = "application/json";

这样,请求将要求服务器以 JSON 格式返回结果,这可能对您更有用。 如果失败,则必须从 HTML 中提取内容,构造一个对象,然后将该对象序列化为 JSON。

【讨论】:

  • 返回json不起作用...如何从html中提取内容?
【解决方案2】:

将 HTML 解析为 JSON 的最佳方法是

  1. 使用 HTML Agility Pack 解析 HTML。
  2. 根据您的 HTML 中的内容,您可以在 c# 中创建一个类并为其创建一个对象,或者如果 HTML 内容重复,您可以创建一个对象列表。

    Class MyItem
    {
        int employeeId = 0;
        string employeeName = String.Empty;
    }
    
    List<MyItem> list = new List<MyItem>();
    JavaScriptSerializer js = new JavaScriptSerializer();
    js.Serialize(list);
    

【讨论】:

    【解决方案3】:

    我会告诉你为什么你的问题会引起混淆。考虑 html 的例子:

    <html>
    <body>
    <p> example of paragraph </p>
    </body>     
    </html>
     Example of json:
    
    {"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
    ]}
    

    json 是某种东西,在其上生成 html 或初始基础。因此,当您说要将 html 转换为 json 时,这确实令人困惑,因为无法弄清楚您要根据哪些规则进行此转换。或者在创建 json 时应该忽略/添加来自 html 的哪些标签。

    【讨论】:

    • 我只想在我的 json 中添加该 html 响应中表中的行
    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2016-06-16
    • 2019-05-27
    • 2015-09-09
    • 2018-12-13
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多