从响应流中获取JSON数据并将其作为字符串读取?

时间:2021-01-25 19:34:02

I am trying to read a response from a server that I receive when I send a POST request. Viewing fiddler, it says it is a JSON response. How do I decode it to a normal string using C# Winforms with preferably no outside APIs. I can provide additional code/fiddler results if you need them.

我正在尝试从发送POST请求时收到的服务器读取响应。查看fiddler,它说这是一个JSON响应。如何使用C#Winforms将其解码为普通字符串,最好不使用外部API。如果您需要,我可以提供额外的代码/提琴手结果。

The fiddler and gibberish images:

小提琴和乱码图像:

从响应流中获取JSON数据并将其作为字符串读取?从响应流中获取JSON数据并将其作为字符串读取?

The gibberish came from my attempts to read the stream in the code below:

我试图在下面的代码中读取流:

Stream sw = requirejs.GetRequestStream(); 
sw.Write(logBytes, 0, logBytes.Length); 
sw.Close(); 
response = (HttpWebResponse)requirejs.GetResponse();
Stream stream = response.GetResponseStream(); 
StreamReader sr = new StreamReader(stream); 
MessageBox.Show(sr.ReadToEnd());

2 个解决方案

#1


14  

As mentioned in the comments, Newtonsoft.Json is really a good library and worth using -- very lightweight.

正如评论中所提到的,Newtonsoft.Json确实是一个很好的库,值得使用 - 非常轻量级。

If you really want to only use Microsoft's .NET libraries, also consider System.Web.Script.Serialization.JavaScriptSerializer.

如果您真的只想使用Microsoft的.NET库,还要考虑System.Web.Script.Serialization.JavaScriptSerializer。

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());

#2


3  

Going to assume (you haven't clarified yet) that you need to actually decode the stream, since A) retrieving a remote stream of text is well documented, and B) you can't do anything much with a non-decoded JSON stream.

假设(你还没有澄清)你需要实际解码流,因为A)检索远程文本流已被充分记录,并且B)你不能对未解码的JSON流做任何事情。

Your best course of action is to implement System.Web.Helpers.Json:

您最好的方法是实现System.Web.Helpers.Json:

using System.Web.Helpers.Json
...
var jsonObj = Json.Decode(jsonStream);

#1


14  

As mentioned in the comments, Newtonsoft.Json is really a good library and worth using -- very lightweight.

正如评论中所提到的,Newtonsoft.Json确实是一个很好的库,值得使用 - 非常轻量级。

If you really want to only use Microsoft's .NET libraries, also consider System.Web.Script.Serialization.JavaScriptSerializer.

如果您真的只想使用Microsoft的.NET库,还要考虑System.Web.Script.Serialization.JavaScriptSerializer。

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());

#2


3  

Going to assume (you haven't clarified yet) that you need to actually decode the stream, since A) retrieving a remote stream of text is well documented, and B) you can't do anything much with a non-decoded JSON stream.

假设(你还没有澄清)你需要实际解码流,因为A)检索远程文本流已被充分记录,并且B)你不能对未解码的JSON流做任何事情。

Your best course of action is to implement System.Web.Helpers.Json:

您最好的方法是实现System.Web.Helpers.Json:

using System.Web.Helpers.Json
...
var jsonObj = Json.Decode(jsonStream);