Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSON data from a response stream and reading it as a string?

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());
like image 714
Chris Altig Avatar asked Dec 07 '13 03:12

Chris Altig


People also ask

How do I convert a JSON to a string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Is JSON response a string?

A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON. parse() , and the data becomes a JavaScript object.

Can JSON be stored as a string?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Which method helps to extract the JSON body content from the response?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


2 Answers

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());
like image 61
stames Avatar answered Nov 03 '22 14:11

stames


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);
like image 37
brandonscript Avatar answered Nov 03 '22 15:11

brandonscript