Question

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.

The fiddler and gibberish images:

GibberishJSON

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());
Was it helpful?

Solution

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

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

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

OTHER TIPS

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.

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

using System.Web.Helpers.Json
...
var jsonObj = Json.Decode(jsonStream);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top