在c#中将html转换为json

ryoqjall  于 2022-11-26  发布在  C#
关注(0)|答案(4)|浏览(240)

我有一个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();
xxls0lw8

xxls0lw81#

根据端点的不同,您可能会在请求中添加一个 Accept 头,要求JSON。
我不知道可能在 WebRequest 上设置了什么属性,但它可能类似于

request.Accept = "application/json";

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

gorkyyrv

gorkyyrv2#

将HTML解析为JSON的最佳方法是
1.使用HTML Agility Pack解析HTML。
1.根据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);
mwg9r5ms

mwg9r5ms3#

我会告诉你为什么你的问题会引起混乱。考虑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中的哪些标签应该被忽略/添加。

ioekq8ef

ioekq8ef4#

没有直接的方法将HTML转换为JSON。
然而,我发现最简单的方法是直接从浏览器复制/粘贴HTML到Excel中,并进行一些操作以形成“表”结构。
接下来使用Office Script将Excel转换为JSON。

相关问题