Tom Tom - 2 years ago 153
JSON Question

Convert JSON reponse stream to string

I am trying to do a POST and then read the JSON response into a string.

I believe my issue is that I need to pass my own object into DataContractJsonSerializer but I'm wondering if there is some way to just get the response into an associative array or some sort of key/value format.

My JSON is formatted like: {"license":"AAAA-AAAA-AAAA-AAAA"} and my code is as follows:

using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email)))
string output = new StreamReader(response).ReadToEnd();

DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
string results = json.ReadObject(ms) as string;

licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null);


Answer Source

I'd strongly recommend looking into Newtonsoft.Json:


After adding the reference to your project you just include the following using at the top of your file:

using Newtonsoft.Json.Linq;

And then within your method you can use:

var request= (HttpWebRequest)WebRequest.Create("");
var response = (HttpWebResponse)request.GetResponse();
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();

var json = JObject.Parse(rawJson);  //Turns your raw string into a key value lookup
string licsene_value = json["licencse"].ToObject<string>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download